Johnny
Johnny

Reputation: 612

Instantiated prefab should call a function from the main script?

I want something like this.

ComponentTest.cs - This script is attached to a empty game object in the scene.

public class ComponentTest : MonoBehaviour {

    public GameObject boxPrefab;

    void Start () {

        GameObject temp = Instantiate(boxPrefab, new Vector3(0,0,0), Quaternion.identity) as GameObject;

        temp.GetComponent<PrefabBox> ().go = gameObject.GetComponent<ComponentTest>().Yes();

    }

    public void Yes(){
        print("yes");
    }

}

and PrefabBox.cs - This script is attached to the prefab.

public class PrefabBox : MonoBehaviour {

    public GameObject go;

    void Start () {
        go ();
    }

}

I get this as error:

The member `PrefabBox.go' cannot be used as method or delegate

Upvotes: 1

Views: 276

Answers (1)

Christian
Christian

Reputation: 1577

First of all, the go object is declared as a GameObject but then you assign a function to it and then call it like a function.

It looks like you want Closures in which you can store functions to variables and call them in the way you do.

This post covers it: http://answers.unity3d.com/questions/494640/capturing-a-variable-in-a-closure-behaves-differen.html

Seems the data type needs to be Action but best to read up on it to grasp it properly.

Good luck.

Upvotes: 2

Related Questions