Heres the problem,
I have a GameObject script that is trying to Find a Text component on a GameObject in the Canvas.
Here is some code that i’ve tried, all giving null references:
public class PlayerController : MonoBehaviour {
public Text coinText;
void Start ()
{
coinText = GameObject.Find("Canvas/coinText").GetComponent[UnityEngine.UI.Text]();
}
void example ()
{
coinText.text = coins.ToString ();
}
}
Ive also tried Find(“Canvas/coinText”).GetComponent
I’ve found the problem.
So I was trying to Find() a few GameObjects, one of which was inactive, which didn’t matter, I was happy to just fix it up later, but the problem was that ‘that’ GameObject, which was inactive, was not just returning null, like the others, it WAS finding the inactive GameObject, but instead of coming back as null, or just ignoring it, it was being considered an error in the function itself, and so everything after that line was getting dropped. So the other Find() calls worked as long as i put them before the inactive Find() call.
(I’ve removed that line since)
Unity Scripting API says “This function only returns active game objects.” Which is fine, but what it doesn’t mention is that if the GameObject you are looking for is not active, it doesn’t return null, it drops the rest of the function without giving an error. (Which can be problematic if someone tries to check a GameObject’s active state with Find() calls)
This should be fixed, reworked, or at the very least mentioned in the documentation, it’s not intuitive to know this.
On further thought, I can’t see why Find() can’t be used to store inactive GameObjects into variables, when you can do it manually through the Hierarchy and inspector, with no problems. And by what i’ve just discovered, it shows that it DOES find the game object, it just refuses to handle it.
have you tried:
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
public Text coinText;
void Start(){
coinText = GameObject.Find(“coinText”).GetComponent