How to free a loaded resource?

Godot Version

4.3

Question

I currently implement a method that automatically loads neighbor scenes to make scene switching faster.

func load_neighbor_scene() -> void:
	neighbor_idx = get_neighbor_idx()
	for scene_idx in neighbor_idx:
		# skip loaded scene
		if scene_idx in loaded_scene.keys():
			continue
		scene_dict[scene_idx] = load(SCENE_PATH % scene_index)
	for scene_idx in scene_dict.keys():
		if scene_idx not in neighbor_idx:
			pass
			# free unused scene

I’m more confused about how to free the already loaded resource. Since it didn’t become a node, free() can’t be used.
Doc says:

When a Resource is no longer in use, it will automatically free itself. Since, in most cases, Resources are contained in Nodes, when you free a node, the engine frees all the resources it owns as well if no other node uses them.

The script is a singleton, it will not be free, while the game is running. I’m not sure if this means that I just need to write scene_dict[scene_idx] = null and the resource will be automatically freed

As you know, PackedScene is a resource, and as you read in the documentation it will free itself if not used, this is because a resource keeps track of where it has been used, so if this code exists in every script you can release it without freeing, now that you have put it in a singleton it should still be able to track usage, although your access system is dynamic so it may never be freed, so you can use scene_dict.erase(scene_idx) to be more sure and yes, if you do this it will free itself.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.