Home > Mobile >  Class variable shows no data after instantiation inside prefab object
Class variable shows no data after instantiation inside prefab object

Time:11-22

I am async loading an addressable prefab which contains a monobehaviour script called Window. Window has string variable "request" that is loaded on instanciation.

Window Class definition

public class Window: MonoBehaviour{
    public string request;
    void Awake(){
        request = "load_data";
    }
}

Code that instanciates the prefab and gets the "Window" reference.

AsyncOperationHandle<GameObject> loadOp = Addressables.LoadAssetAsync<GameObject>(address);
yield return loadOp;
   
if (loadOp.Status == AsyncOperationStatus.Succeeded){          
        var op = Addressables.InstantiateAsync(address);
        if (op.IsDone)
        {
            Window window = loadOp.Result.GetComponent<Window>();
            var data = window.request; <------ this is empty
        }
    }
}

PROBLEM I get empty string in the data variable because window.request is empty. If I debug the code I can see how "Awake" function in Window class is called and variable request is loaded BUT I get empty string later, I dont undertand why.

CodePudding user response:

The Window that is running Awake is the instance created by InstantiateAsync, not the prefab created by LoadAssetAsync. You should refer to the request of the instance:

if (loadOp.Status == AsyncOperationStatus.Succeeded){          
    Addressables.InstantiateAsync(address).Completed  = op => 
    { 
        if (op.Status == AsyncOperationStatus.Succeeded) 
        { 
            Window window = op.Result.GetComponent<Window>(); 
            var data = window.request;
        } 
    };
}
  • Related