Loading (and unloading) resources at runtime causes "hiccups"

In my game I’m loading and unloading resources at runtime. I can appreciate some hiccups sometimes, AFAIK, it should be because garbage collection (also, in profiler I can see it’s caused by Loading.UpdatePreloading > Application.Intergrate Assets in Background > GarbageCollectAssetsProfile)

Is there any way to load and unload resources at runtime, avoiding such hiccups?

When you load an asset, it gets cached. So if you call Resources.Load() on an object, then again later on the same object, the second one will be MUCH faster. Therefore, you can load things once while your level is loading so the hiccup goes unnoticed by the player when you load again later. When you want to unload something, add it to an “unload list”, then wait until it would be appropriate to have a hiccup before you go through the list and unload everything.

Also, if you find that Garbage Collection happens at inconvenient times, you can call GC.Collect() yourself when a hiccup wouldn’t be as bad.

Because I use a lot of hi-res graphics on my level, I want to load and unload while playing. I can’t wait to unload and call GC.Collect() when level finishes.

So, while playing, I’m loading prefabs (objects with an animator and sprites) using Resources.Load, and instantiating them. And then I’m unloading by destroying them and calling Resources.UnloadUnusedAssets(). So I can load and unload tetures while playing.

The problem is the hiccup. Maybe I can use Resources.Unload instead of Resources.UnloadUnusedAssets, so it should be faster. The problem is I don’t know how to use it to unload my loaded prefabs.

Resources.Load() returns an Object, and Resources.Unload() accepts an Object. Like I said, calling Resources.Load() a second time on the same asset without unloading will not load an additional copy of the asset, so to unload a specific asset, you can call Resources.UnloadAsset(Resource.Load(“Asset To Unload”))

Thanks! It worked! I have to unload individual textures instead of prefab, but it works :slight_smile: