Reputation: 101
How do I load an addressable AssetReference dynamically, like a crate or something, via LoadAssetAsync and then reuse it throughout my game without calling LoadAssetAsync again?
I am generating a series of square platforms that are addressable objects. When each platform is spawned, it generates its own set of addressable objects to populate the platform. The objects for each platform are assigned to an array of AssetReferences via the inspector. Using the code below, I am able to loop through the array and generate the objects for the platform. My problem is that when the next platform tries to generate its objects via LoadAssetAsync I get the error
Attempting to load AssetReference that has already been loaded.
I get that the objects have already been loaded, so doing it again makes no sense. How can I access the addressables, test that they are in the scene, and duplicate them as prefabs for future platforms?
I think this is probably simple, and I am just missing something basic, but I can't figure it out.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class SquareObjectsDistributor : MonoBehaviour
{
public SquareObject[] SquareObjectArray;
[System.Serializable]
public class SquareObject {
public string sqObject;
public AssetReference sqObjectReference;
public Vector3 sqObjectPosition;
public Vector3 sqObjectRotation;
}
public void DistributeObjects(int whichSquare) {
for(int i = 0; i < SquareObjectArray.Length; i++)
{
InstantiateSquareObjects(whichSquare, i);
}
}
void InstantiateSquareObjects(int whichSquare, int whichObject) {
Debug.Log("Object_" + whichSquare + "_" + whichObject);
SquareObjectArray[whichObject].sqObjectReference.LoadAssetAsync<GameObject>().Completed +=
(asyncOperationHandle) => {
if(asyncOperationHandle.Status == AsyncOperationStatus.Succeeded) {
GameObject newObject = Instantiate(asyncOperationHandle.Result, SquareObjectArray[whichObject].sqObjectPosition, Quaternion.Euler(SquareObjectArray[whichObject].sqObjectRotation)) as GameObject;
newObject.name = "Object_" + whichSquare + "_" + whichObject;
} else {
Debug.Log("Failed to load");
}
};
}
}```
Upvotes: 0
Views: 211