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 = 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";
}
}