Giuseppe Toto
Giuseppe Toto

Reputation: 225

Free the memoy Destroy Prefab

I'm making an interactive comic in 2D, divided into "episodes". At the moment I'm working on memory optimizations using Unity Profiler.

My goal is to load in RAM only the episode that the user has chosen to look at.

To do this I'm using :

GameObject prefab = Resources.Load ("name_prefab") as GameObject; 
GameOject obj = Instantiate (prefab) as GameObject; 

When I destroy the episode do the following commands :

Destroy (obj); 

obj = null; 

Resources.UnloadUnusedAssets (); 

but the memory usage does not change as I expected.

What am I doing wrong?

In the alternative use of assetBundle I'm doing but I would prefer avoid them because at the time the episodes are only present locally then it would seem like a waste.

Here is another post that has the same problem better explained but he had no answer.

Upvotes: 4

Views: 2657

Answers (1)

S.C.
S.C.

Reputation: 920

Resources.UnloadUnusedAssets(); frees memory allocated to asset objects which are out of scope. In the code snippet you provided, the reference to the prefab still exists. This is probably the main reason why the prefab still lingers in the memory.

Even if there are objects marked as "should be destroyed", the memory allocated to these objects is not immediately freed. It is the job of the garbage collector running behind the scene to decide when should the lingering garbage be cleaned up.

Garbage collection involves expensive operations which bring impact to performance. That is why the garbage collector will do its job occasionally. Usually, it does its job when you are changing scenes or when the memory usage hits certain thresholds. There are many articles can be found on the internet. I believe the official manual can give you a basic understanding on this topic.

Unity states that changing scenes will wipe out everything the original scenes except the objects marked as not to be destroyed by DontDestroyOnLoad(targetObject);. If you really care about the memory usage, maybe you can try to modify the structure of the application a bit. So each episode is saved as a scene, rather than a prefab.

Upvotes: 1

Related Questions