I’m sure that this is a simple question regarding the new UI system… One that’s probably been asked a million times, but I can’t seem to locate the answer by searching the forums (My search-fu is lacking)…
I have a Text object in my canvas and a script attached to a game manager (empty) object to deal with various things. For whatever reason, the following code is failing with a null reference exception in the Start function (which of course means that ClickedButton will also fail). I’ve double checked all of the object names with no success. Is it not possible to use GameObject.Find with the new UI components? Or is there something I’m missing?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class MenuManager : MonoBehaviour {
public Text my_text;
void Start() {
my_text = GameObject.Find("text_object_name").GetComponent<Text>();
}
public void ClickedButton() {
my_text.text = "Testing...";
}
}
sigh COMPLETELY disregard!!! (I don’t think I can delete the thread)
Apparently I was in “play” mode while checking the names, so they didn’t take. ForeheadSlap()
You helped me with the “.GetComponent()” part of the Start method so this thread was not useless already
I just couldn’t figure out how to .Find a UI Text gameobject…
ANYWAYS Thanks
you can do other think to find Text :
public GameObject obj;
public Text txt;
void Start(){
obj= GameObject.Find(“name_of_obj_in_scene”);
txt= txt.GetComponent();
}
// it’s same object , first declare as gameObject and after getComponent as Text
Good Luke
public GameObject Canvas; //Var to get the player UI Canvas
And use this where you want (function or Update() for ex)
Canvas = GameObject.Find("PlayerUI"); // PlayerUI : my Player UI Canvas
foreach (Transform eachChild in Canvas.transform) {
if (eachChild.name == "Score") { // Score : my GameObject where is the Text with the Player Score
foreach (Transform eachChild2 in eachChild.transform) {
if (eachChild2.name == "points") { // The Child of Score : the Text object...
//Debug.Log ("Child found. Name: " + eachChild2.name);
Score = eachChild2.GetComponent<Text>();
}
}
}
}
So now you don’t have to drag & drop a txt GameObject (UI) into a [SerializeField] var
I’ve spend hours, like you, to find a solution. Maybe we can do a recursive function to simplify…
For those comming from 2020 make sure that you use Text and not Text mesh pro in order to use GameObject.Find(“Name of text in scene hirarchy”).GetComponent().text = “your new text”;