- Home /
How to get a Text child, when there are many Text childs
hello,
i instantiate a prefab (monster-card) to UI. this monster-card-prefab has many text fields, like name, health, attack, description, ...
now i will change the description of this card, but how acces exactly a particular Text element.
but with this i get only the first text element of this card and it changes the name :
newText = newCard.GetComponentInChildren<Text>();
newText.text = "new description"
Answer by Ali-hatem · Apr 10, 2016 at 08:59 AM
you need GetComponentsInChildren
not GetComponentInChildren
:
Text [] newText ;
void Start () {
newText = GetComponentsInChildren<Text> ();
newText [0].text = "name";
newText [1].text = "health";
newText [2].text = "attack";
newText [4].text = "description";
}
Answer by JoshuaMcKenzie · Apr 10, 2016 at 08:46 AM
easiest way is to have the script have multiple public Text variables
public Text Name;
public Text Health;
public Text Attack;
public Text Description;
then you set them inside inspector in unity. now in script you can simply set Description.text. this is useful as it makes your code transparent and easier to read by other programmers
Otherwise lets say that the game object is created dynamically during runtime and you can't have those inspector values preset. then you can instead use GetComponentsInChildren(). thats with an "s". which will return an array of all Text components in the children, ordered in the same order as they were placed in the heirarchy.
thank you for the fast answer.
yes, it is created dynamically during runtime. and now how to access the description element with GetComponentsInChildren() ?
Answer by junedmmn · Oct 26, 2018 at 04:48 PM
This might be the easiest to change color of children of a gameobject, you can modify the code to suit your requirement
public void ChangeColor()
{
foreach (Text text in gameobject.GetComponents.InChildren<Text> ())
{
text.color = new Color(1f, 0, 0, 1f);
}
}
Your answer
Follow this Question
Related Questions
Access and modify Text within a prefab 1 Answer
Graphic problem with UI Text 2 Answers
New UI: change text 2 Answers