Are instanced scenes freed when not added as a child?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sotlol

Let’s say there’s a list of items I need to iterate over. But since they’re packed scenes, the only way I can access a variable like ‘cost’ is by instancing it like this.

var _ar = []
for i in _list:
	var _inst = i.instantiate()
	if _inst.cost >= pProfile._cash:
		_ar.append(i)

If this was run every frame would this cause a memory leak and would I have to free it manually?

:bust_in_silhouette: Reply From: cmdrsteel

Nodes have to be manually removed if they are manually added. Scenes extend node. So yes this is a recipe for disaster, especially if you are running this every frame. You have a couple of options.

Create the packed scenes only as you need them, and then remove them manually when you are done. I had to do that in the past, since I made a game that programmatically made dozens of packed scenes every frame, and sent it flying past for the player to click. I originally had it removed from the tree once it went off screen, or clicked, but it slowed down the game so much as time went on. Once I used queue_free(), the performance problems went away.

Another: Separate some of the important data you need all the time from the scene as a global variable, or into a separate class that extends RefCounted. That way you don’t need to delete it manually. Either the global variable never gets deleted, or the RefCounted will delete itself when you are finished. Very helpful if you need information and important functionality, but not necessarily the audio/visual stuff.