I have a GameObject with a TextMeshProUGUI as a child, and I'm trying to create copies of this GameObject via script and then change the text of the TMP child. I have the parent GameObject successfully created, and I can see that the child is there, however using GetChild() only returns a transform object type, which doesn't have the method I need (specifically the text field).
public GameObject goGoalBtn; // this is in the variable declarations
//other stuff here
public void spawnGoalDisplay(string goalDispName, int goalDispType=0) {
GameObject goGoalDisplay = (GameObject)Instantiate(goGoalBtn);
// this works
Transform newGoalDisplay = goGoalDisplay.transform.GetChild(0);
Debug.Log("newGoalDisplay: " newGoalDisplay.name);
// this doesn't work
TextMeshProUGUI newGoalDisplay = goGoalDisplay.transform.GetChild(0);
Debug.Log("newGoalDisplay: " newGoalDisplay.text); // this is what I need to read/write
}
I can't seem to find a way to change the child's object type to TextMeshProUGUI. Is it possible to set the type of the child object returned with GetChild() to something other than Transform? Or a different way to get the child of an object (I tried goGoalDisplay.child(0) but that didn't work either) that lets me set the object type?
I think I could possibly bypass this issue by instantiating the GameObject and then instatiate the TMP and then set it as a child of the parent GameObject, and destroy the first child, but that seems ... unnecessarily complex, so I'd like to use a better solution if one exists. I'm fairly new to C# and Unity3D and would appreciate any assistance.
CodePudding user response:
What about either
TextMeshProUGUI newGoalDisplay = goGoalDisplay.transform.GetChild(0).GetComponent<TextMeshProUGUI>();
or diectly
TextMeshProUGUI newGoalDisplay = goGoalDisplay.GetcomponentInChildren<TextMeshProUGUI>();
CodePudding user response:
transform.GetChild() will return the Transform of that GameObject. if you want to access the TextMeshProUGUI component you could simply do the following,
TextMeshProUGUI newGoalDisplay = goGoalDisplay.transform.GetChild(0).GetComponent<TextMeshProUGUI>;
Now I am assuming that the first child of your goGoalDisplay has TextMeshProUGUI component attached to it, otherwise it will throw a null reference exception when you will try to debug the text.
