Balanivash
Balanivash

Reputation: 6867

Unity3D : Unable to change TextMesh in instantiated object

I instantiate an object and change the text mesh inside it using the below code.

GameObject folder = (GameObject)Instantiate(prefab,<newLocation>,Quaternion.identity);
folder.name = "Folder1";
TextMesh content = GameObject.Find("Folder1").transform.GetChild(0).transform.GetChild(3).
                     gameObject.GetComponent<TextMesh>();
content.text = "New Content";

But, when I run the scene, the text mesh still has the value from the prefab and is not updated. Has anyone faced a similar issue or any idea on how to resolve it?

Upvotes: 1

Views: 358

Answers (2)

Everts
Everts

Reputation: 10701

You mentioned that the item gets updated properly but then when you create new ones, it does not work anymore.

I would think your problem is that you are naming them with the same name "Folder1". Then you are looking for an object called Folder1 and the first one is returned.

GameObject folder = (GameObject)Instantiate(prefab,<newLocation>,Quaternion.identity);
folder.name = "Folder1";
TextMesh content = folder.transform.GetChild(0).transform.GetChild(3).
                     gameObject.GetComponent<TextMesh>();
content.text = "New Content";

this could fix your problem. Notice this is no longer looking for an item but using the reference from the new object.

Upvotes: 1

HoloLady
HoloLady

Reputation: 1043

Are you sure you're getting the right object? Your GetChild's are a bit worrying. Maybe you can try giving your object a tag and searching for that instead. So, you set the tag of the gameobject that has your textmesh to HasTextMesh and then in your code do:

GameObject folder = (GameObject)Instantiate(prefab,<newLocation>,Quaternion.identity);
TextMesh content = GameObject.FindWithTag("HasTextMesh").GetComponent<TextMesh>();
content.text = "New Content";

Upvotes: 0

Related Questions