I have a List that I loop through on Awake, and I load them individually.
For an example, let’s say my lists contents are: assetA, assetA, assetB, assetA.
I’m using a foreach loop to pre-load the assets one-by-one like this:
foreach (AssetReference reference in references)
{
if (reference.Asset != null) continue;
loadHandle = reference.LoadAssetAsync<GameObject>();
yield return loadHandle;
}
If the list is like the example above, I’m expecting the second & fourth element’s .Asset to be defined, as the first element should already load that asset.
What I’ve done to prevent loading same AssetReference multiple times is to add reference.editorAsset.name to a dictionary (with the GameObject as value), and instead of checking whether refernce.Asset != null, I just check if that name exists already in the dictionary.
This works fine for now, but was just wondering why doesn’t the Asset property get set for the other elements of the list of they are the same AssetReference?
An AssetReference is a class, but even if you have a list of them. When the scene is serialised/deserialised, they will each be serialised as a unique instance. This is unless you have a [SerialisedReference] tag.
So you are interacting on each.
Internally load calls are cached (Though there is some overhead with locating the asset info and such), so loading something already loaded, will retrieve it from the cache.
Using .editorAsset is ofcourse only viable in the editor, it also loads the asset in the editor. So if you are using built content play mode, you will double up on memory. Though usually not a problem in the editor.
If you use .runtimeKey, this is the GUID of the asset, and is a unique string per asset.
As you mentioned, I had to change the .editorKey to .runtimeKey and it has been working fine so far.
What I’m doing in my case is that I have a list of enemies to spawn in a specific level (list of asset references), that are loaded after a level is loaded. I loop through this list of references and load them one by one, and store the loaded asset to a dictionary with the .runtimeKey being the key. Not sure if necessary, but this prevents me from loading the same asset many times (for example if a level has 5x of one type of enemy, I only load the asset once).