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?
public AssetReferenceGameObject gameObjectReference;
private void InstantiateGameObject(){
string foo = "This variable wants to be passed to DidLoadGameObject()";
gameObjectReference.InstantiateAsync(Vector3.zero, Quaternion.identity, null)
.Completed += DidLoadGameObject;
}
private void DidLoadGameObject(AsyncOperationHandle<GameObject> op)
{
GameObject go = op.Result;
Text textComponent = go.GetComponentInChildren<Text>();
textComponent.text = foo; // <- This obviously will fail, how to pass that variable to make this work?
}
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:
public AssetReferenceGameObject gameObjectReference;
private void InstantiateGameObject()
{
string foo = "This variable wants to be passed to DidLoadGameObject()";
gameObjectReference.InstantiateAsync(Vector3.zero, Quaternion.identity, null)
.Completed += (AsyncOperationHandle<GameObject> op) =>
{
GameObject go = op.Result;
DidLoadGameObject(go, foo);
};
}
private void DidLoadGameObject(GameObject go, string foo)
{
Text textComponent = go.GetComponentInChildren<Text>();
textComponent.text = foo;
}