Best practice - Remove GUI object from scene

Hello! I have a Class named CoinEffect which I created each time a player do a combo in my game. This Class contained several GUI element such as images, textblocks…

All GUI element in this Class are animated on the runtime (position, scale, rotation, alpha…). When the animation is done, I want all the GUI element to be destroy.

What is the better way to remove/destroy GUI element from a scene ?

Pseudo code below - which one is the solution and/or is there a better way to avoid any memory issue at long term?

// Remove object
public disposeUI(): void {
	this.listUIElement.forEach((object: any) => {
		this.app.gameUI.removeControl(object); // #1
		object.dispose(); // #2
		object = null; // #3
	});

	// Clear array
	this.listUIElement = [];
}

If you want to dispose your GUI elements I believe the simplest and the best way is to use dispose() method - Container | Babylon.js Documentation
But if you will dispose elements with forEach function, it will not work properly. See here - Disposing scene.meshes leaving last meshes? - #4 by labris

Other way is to use your class only one time for creation of elements, then make them visible/invisible when needed.

1 Like

And then what, you recreate them on the fly? Seems a bit heavy to me.
What if you would hold all this in a single ADT. Unregister only the runtime animation/function and make the ADT !isVisible.

1 Like