How are Custom Resources (RefCounted) freed?

Godot Version

v4.2.2.stable.official [15073afe3]

Question

I am trying to understand when a custom resource is released from memory in Godot. I see that custom resource inherits RefCounted. And it says:

Unlike other Object types, RefCounteds keep an internal reference counter so that they are automatically released when no longer in use, and only then. RefCounteds therefore do not need to be freed manually with Object.free.

In my script, I create multiple custom resources during runtime, and these resources are passed to other nodes. These nodes uses the resource for some time, then they are not needed anymore. But I never delete the nodes (either the main node that creates the resources or the other nodes that the resources are used in). So Iā€™m not sure, if this will create a memory leak at some point because the script would be creating a lot of new custom resources without freeing it from the memory . Because the node that the resource is created, and the nodes that the resource is passed are almost never deleted (freed)

In Godot, ā€œRefCountedā€ resources are automatically freed when their reference count drops to zero. If your nodes or objects holding references to these resources are never deleted, the resources will remain in memory. To avoid potential memory leaks, ensure that you release references to resources when they are no longer needed by setting them to ā€œnullā€ or removing them from collections.

1 Like

If you want to ā€˜seeā€™ when they get freed you can check the notifications. Iā€™m on the phone right now, canā€™t test it and will keep this short. Pre delete should work for recounted too. This way you can test if your way of freeing works (What Ethan said)

func _notification(what):
	match what:
		NOTIFICATION_PREDELETE:
                        print("good-bye")
2 Likes

Thank you trizZzle and ethan for the reply. They were both useful for me to debug it.

First of all, yes to NOTIFICATION_PREDELETE suggestion. It shows if custom resources are being freed .

I realized that godot is acting pretty smart. I use the same methods in the nodes to pass the custom resources. So the same variable will reference to a new custom resource, while the old one wonā€™t be referenced anymore. So I think godot checks this and if thereā€™s no variable referencing to that custom resource, it frees it, even though the node is still there. I think itā€™s the same logic of making the variable ā€˜nullā€™ as ethan suggested.

2 Likes

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