Search Unity

Question Pass variable from InstantiateAsync to DidLoad;

Discussion in 'Addressables' started by jeppe79, Aug 2, 2020.

  1. jeppe79

    jeppe79

    Joined:
    Sep 17, 2019
    Posts:
    75
    Hello,

    In this example, is it possible to pass a variable from InstantiateGameObject() to DidLoadGameObject() ?
    I don't want to use a global variable and I can't make DidLoadGameObject() anonymous as I have several other references to DidLoadGameObject().
    How can I achieve this?


    Code (CSharp):
    1.     public AssetReferenceGameObject gameObjectReference;
    2.  
    3.     private void InstantiateGameObject(){
    4.         string foo = "This variable wants to be passed to DidLoadGameObject()";
    5.         gameObjectReference.InstantiateAsync(Vector3.zero, Quaternion.identity, null)
    6.         .Completed += DidLoadGameObject;
    7.     }
    8.  
    9.     private void DidLoadGameObject(AsyncOperationHandle<GameObject> op)
    10.     {
    11.         GameObject go = op.Result;
    12.         Text textComponent = go.GetComponentInChildren<Text>();
    13.         textComponent.text = foo; // <- This obviously will fail, how to pass that variable to make this work?
    14.     }


    OK..... SO....... I made a work around by using an anonymous function to pass the variable... the questions is, is this bad practice?
    It will fill all my needs, but it doesn't look very pretty.
    Any better solutions are most welcome.


    Solution:
    Code (CSharp):
    1. public AssetReferenceGameObject gameObjectReference;
    2.  
    3. private void InstantiateGameObject()
    4. {
    5.     string foo = "This variable wants to be passed to DidLoadGameObject()";
    6.     gameObjectReference.InstantiateAsync(Vector3.zero, Quaternion.identity, null)
    7.     .Completed += (AsyncOperationHandle<GameObject> op) =>
    8.     {
    9.         GameObject go = op.Result;
    10.         DidLoadGameObject(go, foo);
    11.     };
    12. }
    13.  
    14. private void DidLoadGameObject(GameObject go, string foo)
    15. {
    16.     Text textComponent = go.GetComponentInChildren<Text>();
    17.     textComponent.text = foo;
    18. }
     
    Last edited: Aug 2, 2020
  2. ProtoTerminator

    ProtoTerminator

    Joined:
    Nov 19, 2013
    Posts:
    586
    That is the correct way to do it. Nothing wrong with it. I would just shorten it if you don't like it so long:

    Code (CSharp):
    1. .Completed += op => DidLoadGameObject(op.Result, foo);
     
    thephox1982 and jeppe79 like this.
  3. jeppe79

    jeppe79

    Joined:
    Sep 17, 2019
    Posts:
    75

    Thanks a lot for the input! That looks better to me.
    Big cheers!