Question about References and Weakreferences

Hello, I understand the difference between a normal reference and a weak reference. However, I would like to know whether it is better to use a WeakRef property in a script or a normal reference. For example, I want to pass the player node to another node. I will most likely use C#.

I honestly wouldn’t worry about the weak references until you absolutely need to use them to optimize your memory usage. For >99% of the use cases, the normal reference is well enough and using a weak reference won’t make any difference.

I was worried about circular references. Thats why i ask.

Did you already encounter any issue with the circular references that you need to resolve?

Weak reference is only suitable for cases where you have an object A that holds a reference to object B, and the same object B holds a reference to object A. In such a case, both of these might never be freed from memory automatically by the engine unless you free them manually. But as mentioned before - in most cases you shouldn’t need to worry about that unless you specifically need to optimize your memory usage. And if you misuse the weak reference, some objects might be freed from memory when you don’t expect them to.
So to answer your original question: no, it’s usually not better to use a weak reference.

Yes, I have this case in my inventory system. In one scene, the player takes a reference to the grid control I created, and the inventory node within the player tree sets itself as a reference to the grid control. For this, I use a weakptr.

That’s fine, but the regular reference would probably work just fine in this case as well, so it might be just an unnecessary overcomplication.

ok to make sure everything gets deleted i can use _ExitTree() and set the fields to null ?

Nodes aren’t RefCounted objects so weakref() does nothing. You have to manually free() them.

2 Likes

So if i want to free an field within an script i just set it within the _ExitTree() function to null ?