Hi,
When you assign a prefab in the inspector, it would normally load once the scene is loaded taking up memory even if it’s not instantiated until later.
I am pretty sure there was a new feature in some Unity version where you can assign the prefab in the inspector but only load it when you need it, then you can instantiate it after you manually loaded the prefab in code.
I forgot the feature’s name but I need to use it now.
I searched for the feature but I can’t find it even though I am sure I read about it somewhere.
Thanks for advance.
Edit
Actually no, I was wrong. LazyLoadReference does not seem to be used in monobehaviors. I do remember something similar used in monobehaviors.
I think I found it.
LazyLoadReference can be used for that.
But I feel like there was another feature similar to this that gives you more flexibility with loading/unloading.
There doesn’t seem to be a way to unload LazyLoadReference asset after it’s loaded.
Is there such a feature?
I finally found it.
It’s AssetReference!
Explanation on how to use it for lazy loading found here .
Finally!
I thought I was getting crazy.
1 Like
Hey @Stranger-Games , Thank you for sharing your founding.
These are really helpful.
I previously had a problem related to Prefab auto loading.
Today by accession I found LazyLoadReference and thought that could fix Prefab loading issue.
Started researching more about this class and found your thread :).
In your thread I found also AssetReference.
Thank you very much.
For anyone else in the future, wondering how to unload LazyLoadedReference assets once they’ve been loaded, try the following (you can put it in a static class to have it available as an extension method):
public static void UnloadLazyLoadedAsset<T>(this LazyLoadReference<T> lazyLoadedAsset)
where T : UnityEngine.Object
{
var instanceId = lazyLoadedAsset.instanceID;
var o = lazyLoadedAsset.asset;
// I'm not sure if there will be an error trying to access .asset after it has been unloaded,
// so let's set it to null to be safe
lazyLoadedAsset.asset = null;
Resources.UnloadAsset(o);
// we need to restore lazyLoadedAsset.instance id to the remembered instanceId because
// lazyLoadedAsset.asset=null will cause lazyLoadedAsset.instanceId to become 0
lazyLoadedAsset.instanceID = instanceId;
}