Instantiate prefab (button, texture) with attached script

Hey guys,

So here’s my issue, I want to instantiate multiple prefabs with different components in the attached script and set the prefab child button Onclick to a function located in the script.

GameObject prefab;
public GameObject parentGameObject;

void LoadPrefab() {

prefab = (GameObject)Instantiate(Resources.Load("MyPrefab"));
prefab.transform.localScale = new Vector3(1,1,1);
prefab.GetComponent<MyScript>().DataInt = Data;
prefab.GetComponent<MyScript>().DataVector = DataVector.point;
prefab.transform.Find ("btn_goTo").GetComponent<Button> ().onClick.AddListener (delegate {prefab.GetComponent<MyScript>().FunctionInMyScript();}); }

The aim is : when the user click on the button, my camera is moving to the DataVector position.
Now each prefab seems to have the same script attached… How can I fixed this ?
Thanks in advance ! :slight_smile:

It seems you are adding your “MyScript” twice.

Are you sure the data you set to your script are different at least ? Add Debug.Log when changing the value !

By the way, it would be clearer and more efficient to write something like this :

private GameObject newObject;
public GameObject parentGameObject;

void LoadPrefab()
    MyScript myScript ;
    newObject = (GameObject)Instantiate(Resources.Load("MyPrefab"));
    myScript = newObject.AddComponent<MyScript>();

    newObject.transform.localScale = new Vector3(1,1,1);

    myScript.DataInt = Data;
    myScript.DataVector = DataVector.point;
    newObject.transform.Find ("btn_goTo").GetComponent<Button> ().onClick.AddListener ( delegate {myScript.FunctionInMyScript();} );