How would I access a property of another objects child component?

In my Unity 5 project I have a controller script. I want to write code to change the text in the text property of the Text object which is the child of the UI Button object. My controller script is not attached to anything.

My head is spinning from reading about GetComponent, GameObject.Find, and Transform.find.

GameObjects do not hold information about parents or children. To get information about this you have to get the objects Transform. So you could very simply use:

var button : Transform = GameObject.Find("PutButtonNameHere").transform;

var childOfButton = button.GetChild(0); //Gets the object at the top of the list of the button's children.

If you would like to check how many children something has you could do:

var numberOfChildren = button.GetChildCount; /*returns an integer, which will tell you how many children the object has.*/

So to change the Text in the child object you would do:

button.GetChild(0).GetComponent(Text).text = "Your Text";

Hope this was what you wanted.



In C#:

button = GameObject.Find("buttonName").transform;//Same as JavaScript
button.GetChild(0).GetComponent<Text>().text = "Text to change to"; //You need to use more than and less than signs instead with C#, also be sure to include the parentheses after them.

But the most important thing for you to do is, at the top of your script, below "using System.Collections, place this line:

using UnityEngine.UI;

And when I did var button : Transform; in JavaScript, You should have done:

 Transform button;

Complete code I used was:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GameController_C : MonoBehaviour {
	Transform button;
	// Update is called once per frame
	void Update () {
		button = GameObject.Find("Canvas").transform; //My parent was called Canvas, put the name of your parent there.
		button.GetChild(0).GetComponent<Text>().text = "1"; 

Thanks for that, I can almost smell victory.

I’m not quite sure what this is about …

var button : Transform

I’m guessing it’s JavaScript and I’m using C# or maybe my Visual Studio is being fussy.

Anyway, I’m trying this …

var button = GameObject.Find("buttonName").transform;
button.GetChild(0).GetComponent(Text).text = "1";

but I’m getting an error on the Text of GetComponent(Text) “Text is a type which is not valid in the given context”. I get the same with …

Transform button;
public void doButtonThing()
button = GameObject.Find("buttonName").transform;
button.GetChild(0).GetComponent(Text).text = "1";