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

Resolved InstanstiateAsync of generic type

Discussion in 'Addressables' started by alchemist_wurzelpurzel, Oct 26, 2022.

  1. alchemist_wurzelpurzel

    alchemist_wurzelpurzel

    Joined:
    Sep 4, 2018
    Posts:
    43
    Hi all,

    I must be overlooking something because otherwise this might be a missing feature for quite a common use case, or so I think.

    I have a prefab with a Script component on it.
    I have created a custom AssetReference class to reference this prefab:
    Code (CSharp):
    1. [Serializable]
    2.     public class PrefabComponentAssetReference : AssetReferenceT<PrefabComponent>
    3.     {
    4.         public PrefabComponentAssetReference (string guid) : base(guid)
    5.         {
    6.         }
    7.     }
    My goal is to instantiate the prefab using the AssetReference.InstantiateAsync() method and then access the Script component on it like I would with the regular Object.Instantiate method.
    However, I noticed that the AsyncOperationHandle that is returned is always of type GameObject, thus requiring me to make a GetComponent call on the Result once it is done. There seems to be no way to have the Result of my expected type.

    Am I missing something here or is this simply how it's supposed to be used? I really hope this is not the case.

    Thanks!
     
  2. ElevenGame

    ElevenGame

    Joined:
    Jun 13, 2016
    Posts:
    143
    I might be misinformed, but I think that's how you're supposed to use it, get the game object reference and call GetComponent().. Does that really have a performance impact for you? Or why would you prefer a more direct way? Theoretically you could wrap it in a generic method that does GetComponent under the hood of course..
     
  3. alchemist_wurzelpurzel

    alchemist_wurzelpurzel

    Joined:
    Sep 4, 2018
    Posts:
    43
    I guess for our use case it doesn't matter as most of our loading occurs during a loading screen anyways. I had just expected it to work the same way as Object.Instantiate especially since I cannot recall Unity forcing you to make GetComponent calls in other areas.

    Anyways, thank you for your response!
     
    ElevenGame likes this.