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...
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With