- Home /
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.SetParent(parentGameObject.transform);
prefab.transform.localScale = new Vector3(1,1,1);
prefab.AddComponent<MyScript>();
prefab.AddComponent<MyScript>();
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 ! :)
Can you explain better your problem please?, i didn't understand really well unfortunately :(
I'm trying to load n prefabs (with 2 buttons as children) with a same script but different data in it (positions, variables...). In this script I have a function "$$anonymous$$ove" to move my camera to the prefab position. But when I have instantiated more than one prefab, the function "$$anonymous$$ove" move my camera to the same position (the one from the first prefab). I don't know if it's understandable now :/
When in your script is the $$anonymous$$ove function executed? We may need to see more of your script to be able to help.
So you have prefabs with buttons as children, right? You Instantiate these Prefabs all over your map. And when you click on a Prefabs button you want the camera to move to the prefabs position?
Answer by Hellium · Jun 25, 2015 at 02:44 PM
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.SetParent(parentGameObject.transform);
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();} );
}