Addressables and garbage collection

Edit: Sorry, I’m a dope, I somehow missed a glaringly obvious document on needing to call Release. If someone else finds this thread, that article is here:

Memory management | Addressables | 1.3.8.

I’m a bit confused about memory management and Addressables (given that memory management isn’t really a thing I’ve ever worried about)

I’ve lived in a world where I can create objects whenever I bloody-well please and when they stop being referenced, the GC will simply clean them up. However it doesn’t sound like that’s the whole story with Addressables (?)

Let’s say, as part of my GUI, I want to simply load an Sprite Asset from an AssetReference, and assign it to a GUI Image. Later, I load a different Sprite Asset and assign it to the same Image. The original sprite then, isn’t referenced by anything in my code.

What happens? does it get collected, or does something nefarious happen?

Hi!

There is a difference between C# objects and Unity asset references.

When you load a scene, all assets referenced in that scene will be loaded in memory. For example, if you have a list of prefab of enemies, each prefab, with all its material, textures and animation will be in memory when the scene loads. You might never spawn the prefab but it is still loaded.

If you drop the list of prefabs the prefab is still in memory. They exist “outside” the C# engine in unity C++ layer so to speak.

There are a lot of unity objects that are not GC just because you drop the reference to it. Texture2D for example. If you create a new Texture2D it will live inside memory until you call Destory() on it.

You can only count on pure C# objects to be GC:d automatically.

I have found that it is sometimes beneficial to pretend like I’m writing C or C++ code when developing for unity. Just to add an extra step to make me think when things are loaded in and out.

While it’s good to think that way, I’m not sure that’s entirely accurate with regards to textures. They could easily dispose of the C++ texture object from the C# wrapper’s finalizer and not leak anything (whether they do or not is what I’m unsure about). The only thing that doesn’t work on is GameObjects, since the engine holds references to all GameObjects internally just to render the scene.

Woah! that’s wild, I didn’t know that. Thanks!

huh. So I guess then… the rule of thumb is that if it derives from UnityEngine.Object, it needs to be destroyed manually, or by the engine when a scene unloads?

Texture2Ds that you have created using new has to be disposed of manually using Object.Destroy :slight_smile:

1 Like