- Home /
How to get unique reference to instantiated prefab
Hi, I'm looking for a way to create a player GUI using sprites and textmeshes. The game will have up to four players going in turns, and the location of each player's stats will be dependent on the number of players playing, and the randomized order they go in. Therefore, I'm looking to be able to automatically generate these game objects as the game starts up. I want to use clones of prefabs for the textmeshes and sprites to keep the code simple. What I'm discovering is when I try to update either class(in this case Inst), only the last text gets updated.
Here's an example of the class:
public class Inst : MonoBehaviour {
private GameObject textGO; // prefab with a TextMesh
private GameObject textCloneGO;
public void init(int posX){
textGO = Resources.Load("Prefabs/MaxTimeText") as GameObject;
textCloneGO = Instantiate(textGO) as GameObject;
textCloneGO.transform.position = new Vector3(posX,0,0);
textCloneGO.name = "Inst" + posX.ToString();
}
public void setText(string text){
textCloneGO.GetComponent<TextMesh>().text = text;
}
}
This is the class I used to test:
public class InstTest : MonoBehaviour {
private Inst i;
private Inst i2;
void Start () {
i = gameObject.AddComponent<Inst>().GetComponent<Inst>();
i2 = gameObject.AddComponent<Inst>().GetComponent<Inst>();
i.init(-1);
i2.init(1);
i.setText("i1"); // changes i2 to "i1"
i2.setText("i2"); // changes i2 to "i2"
}
}
An explanation as to what's going on, and suggestions on how to get the effect I'm going for would be appreciated.
Answer by DMGregory · May 03, 2014 at 09:36 PM
I think this is your error:
i = gameObject.AddComponent<Inst>().GetComponent<Inst>();
i2 = gameObject.AddComponent<Inst>().GetComponent<Inst>();
Try this instead:
i = gameObject.AddComponent<Inst>();
i2 = gameObject.AddComponent<Inst>();
AddComponent() on its own returns a reference to the newly-instantiated component. By calling GetComponent() from that reference, you get a reference to some component of that type, not necessarily the one you created on that line. In this case, i2 ends up getting a reference to the component created on the line above.
I removed the GetComponent and the code works as expected. Thanks!