I’m trying to use the .dispose() method to get rid of a mesh that’s currently in the scene, and replace it with another. I first noticed an issue when I kept spamming my “import button” and my framerate dropped drastically. I logged scene.meshes to the console only to find that I had hundreds of meshes in my scene! Clearly I was only removing the visibility of the meshes. Right? What am I doing wrong?
Here is the relevant code:
// Get the button from our HTML
let button = document.getElementsByClassName("importButton")[0];
// Add event listener
button.onclick = async () => {
// If the "Example" mesh exists, delete it, import a new mesh, then rename it.
if (scene.getMeshByName("Example")) {
scene.getMeshByName("Example").dispose();
const mesh1 = await BABYLON.SceneLoader.ImportMeshAsync(
"",
"/directory/",
"name",
scene
);
mesh1.meshes[0].name = "Example";
} else {
const mesh1 = await BABYLON.SceneLoader.ImportMeshAsync(
"",
"/directory/",
"name",
scene
);
mesh1.meshes[0].name = "Example";
}
};
Yes, I eventually got the same. Same as you, in my scene, I’m replacing a mesh imported async with a new mesh. From what I figured, I sort of realized that the point is the mesh is not disposed before loading the new one. And then it just adds to it.
To counter this, I’m giving a name to the imported mesh (i.e. displaymesh). Then before importing the new mesh I use the ‘while’ method, checking through all meshes of that name in the scene (of course it induces a small delay) but with this, I’m now sure that I’m not accumulating meshes of ‘displaymesh’.
Something like this:
I would have (or at least I had before changing my script) but I can try find it again.
Though it was basically identical to the script above and really simple. An async function to import async and callind mesh.dispose() before it. I also tried to do a separate dispose only function clearly called before, but I still had the issue of meshes eventually accumulate. And when I say ‘eventually’, also means it didn’t happen everytime.
EDIT_ : Yeah, of course. Now that I’m testing it again, it works
I really don’t know what to say. I think at some point it was importing the model twice. I thought it might be because of the name being given to the parent after the promise but then I tried again and it did not nothing. Next, not understanding what happens, I closed the browser window and refreshed the PG and it was working fine again. Could there be some problem with the caching may be?
EDIT1: Sorry, I polluted the PG a little, adding parts that are not necessary a bit everywhere (in rage ) just to make sure the model was not loading twice because of multiple keypresses or because my variable of _display was not going through. Of course, this is all useless stuff but I guess you got that part