How can I preserve variable values in GUI slider.onValueChangedObservable method?

Hey there, PG here.

I am trying to add a GUI (slider) to my scene, and I want to change the density of my particles when I slide.

My way of changing the density of those particles (created by thin instance) is to remove all of the particles and draw them again. Right now, when you change only ONCE the slider, you can see that the density will be lowered to 10 (on line 180, the second param in the drawPoints method). However, as you click more times in the slider, you can see that the density gets more and more bigger (not very apparent until about 7 times or so), and the fps drop significantly.

======== Question/Current Behavior =======
(1) I still have a doubt on whether the removing particles part (remove thin instances) work on line 177 and 178. If it does NOT remove points, why I cannot see previous points (in the exact same location) as I click the slider (the points generated the second time you click the slider seems to be different than the points generated the first time you click the slider). If it does remove points, why I can see a relative apparent increasing of particles (density values) after I move the slider a few times (7 times).
(2) I tried to add 1 to the variable numInstances after line 184 and log the value of it on line 176 (not in the current PG). I can see that numInstances is not increasing when I move the slider, which makes me to suspect that the variable value is not changed after you click the slider (I declare those variables on line 163 for the first time), which means that sphereP is not the current reference after you move the slider, so it cannot remove the current generated points the second time you click the slider.
(3) also, I would like to know if it is the correct way to remove thin instances

======== Expected Behavior =======
(1) move the slider and change the density of the generated points accordingly

======== Warning ========
(1) my title of this question may not be the most accurate way to express why my scene doesn’t work properly, so I will change it as soon as I figure out the true reason.
(2) I think it might be due to assigning values in JS callback functions, I am checking this rn.

1 Like

The drawPoints function is re-creating the sphere each time it is called. It is not re-using the previously created sphere, and it is not disposing it. This leads to more and more spheres being created each time the slider moves.

I suspect that making the drawPoints function asynchronous is causing some confusion. It looks like the function passed to slider.onValueChangedObservable.add is assuming everything is synchronous.


Hi, sorry for my late reply.
I think you are right, I delete the async code in my drawPoints method, and it works. see my PG.


Very nice!