Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence of GC and unloading assets in Unity3D

Sometimes we need to release useless resources manually in game development. But I'm not sure which is better between

System.GC.Collect();
Resources.UnloadUnusedAssets();

and

Resources.UnloadUnusedAssets();
System.GC.Collect();

AFAIK, both of them are async operations and there might be no difference.

So my question is...

  1. Are there any difference?
  2. If so, which is better?
like image 580
Joon Hong Avatar asked Jul 09 '13 01:07

Joon Hong


People also ask

How do you unload assets in Unity?

To unload assets you need to use AssetBundle. Unload. This method takes a boolean parameter which tells Unity whether to unload all data (including the loaded asset objects) or only the compressed data from the downloaded bundle.

How does GC collect work?

It performs a blocking garbage collection of all generations. All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.

How do I reference assets in Unity?

An "asset" in Unity is file in the Project window such as an AnimationClip , Texture , Prefab, or any script which inherits from ScriptableObject . Very easy to use. Just add a serialized field to your script then drag and drop the asset you want into that field in the Inspector.

Does Unity do garbage collection?

Helpfully, Unity manages your project's memory for you with the Garbage Collector, an automatic memory management system that frees up space for new data allocations as your game runs.


1 Answers

There is no difference between these two kinds.

System.GC.Collect() will tell .Net collector to collect objects which are managed by mono in the managed heap, while Resources.UnloadUnusedAssets deals with assets (textures, sounds and other media) which are put in the native heap. The two method do totally different things, so there is no different which one will be executed first. (As you said, they are both async and you just set a flag to suggest the system it could be a good time to do a collect.)

In fact, it is not so common to call GC collect yourself, except you have a good reason. The GC of system will work in proper time, most of calling for forcing a garbage collect are not so necessary as you think.

If you are wondering more about Unity's memory, you can refer to this blog, which can tell you things in detail.

like image 65
onevcat Avatar answered Sep 27 '22 18:09

onevcat