Crash when disposing an instance

Hi all again.
It seems I can’t do anything without this forum.

https://playground.babylonjs.com/#WXTIHL#8

Instructions:

  • Create a worker by clicking the button
  • leftclick a worker and rightclick the ground near a tree/stone (or vice versa)

Problem: The scene crashes, when an instance is supposed to be disposed.

Further Explenation: When a worker intersects with a tree/stone, it collects ressources (100 for a tree and 50 for a stone) line165 & line 168. If its life reaches zero, it should dispose line 175 - 180 and line 187 - 192.

In my case (not this playground), it crashes, if I create a second worker and collect a tree/stone with it, without collecting with the first worker before. However, in this playground it often crashes with the first worker and the first ressource. And sometimes you can collect just fine.
I can’t figure out, what is causing this. I also tried scene.onBeforeRenderObservable instead of scene.registerBeforeRender, but the result is the same. Does it have to do with the creation of the trees/stones or the worker itself? Or is it something with the dispose function?

I’d be glad for any advice.

Ok…so as you are disposing the mesh inside a loop through scene.meshes, this is expected :slight_smile:


You must first save the scene.meshes into an array like:

var store = scene.meshes.slice(0)

and then iterate through this one as it will remain unchanged (whereas the scene.meshes will be changed by the dispose)

1 Like

Well, that was fast and pretty easy. And probably pretty obvious too.
I feel stupid now :man_facepalming:

Implementing your solution looks like this and seems to work just fine:
https://playground.babylonjs.com/#WXTIHL#10

Thanky you very much for helping me again and again :slight_smile:

No worries:)