Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to access GameObject or Component from AssetReference?

Discussion in 'Addressables' started by dfarjoun, Jun 5, 2020.

  1. dfarjoun

    dfarjoun

    Joined:
    Aug 6, 2017
    Posts:
    42
    Hi,

    I'm trying to have an array of prefabs (loaded as assetReferences) and then accessing their components or normal things that we do with gameObjects.

    But I don't have a clue how to access them.

    I tried this in order to have normal gameObjects and components access... but failed.

    Any help?


    Code (CSharp):
    1. public AssetReference assetToPlaceInScene;
    2.  
    3.     public AssetReference[] assetsToPlace;
    4.  
    5.    
    6.     private List<GameObject> myObjects;
    7.  
    8.     //################
    9.  
    10.     private void Start()
    11.     {
    12.         //load single asset
    13.         assetToPlaceInScene.LoadAssetAsync<GameObject>();
    14.  
    15.         //load array of assets? - Doesn't work
    16.         assetsToPlace[].LoadAssetAsync<GameObject>();
    17.  
    18.  
    19.         //load one item from the assetreference array - looks OK
    20.         assetsToPlace[0].LoadAssetAsync<GameObject>();
    21.  
    22.         //assign assetReference loaded to GameObject List - Doesn't work
    23.         myObjects[0] = assetsToPlace[0].LoadAssetAsync<GameObject>();
    24.  
    25.     }
    Thanks for the support!!
     
  2. Lance-Grooms

    Lance-Grooms

    Joined:
    Mar 24, 2016
    Posts:
    26
    Not quite certain what you are trying to do here, but the LoadAssetAsync produces a AsyncOperationHandle handle for the requests. For each item in your array, you need to make a request and then do something with the Result field if the operation was successful. Hope that helps a little.


    Code (CSharp):
    1.      
    2.         protected override void LoadContent()
    3.         {
    4.             Handle = Addressables.LoadAssetAsync<T>(Address);
    5.             Handle.Completed += OnLoadComplete;
    6.         }
    7.      
    8.         protected void OnLoadComplete(AsyncOperationHandle obj)
    9.         {
    10.             switch (obj.Status)
    11.             {
    12.                 case AsyncOperationStatus.Succeeded:
    13.                     {
    14.                         CONTENT_TARGET = obj.Result as T;
    15.                     }
    16.                     break;
    17.                 case AsyncOperationStatus.Failed:
    18.                     {
    19.                         // FAILED
    20.                     }
    21.                     break;
    22.             }
    23.         }