My code can't see my Canvas object

I have a game object to which I have attached a canvas. When I call the following:

myCanvas = myCanvasHolder.GetComponent ();
Debug.Log (myCanvas.ToString () + " is my starting canvas");

I get back “null is my starting canvas”.

When I try to access this later in the code, I get an error stating that there’s no canvas attached to the object, and I should probably add one… but… but… there IS one. It’s right there!

Any ideas?

Does the GameObject myCanvasHolder contain a canvas?
Try gameObject.GetComponent ();

I created an empty game object (CANVAS_HOLDER), and added to it a canvas (UI → Canvas). Then I added a Text as a child of that Canvas (UI → Text). I can see the text in-game. I cannot for the life of me figure out why my game thinks it’s not there. I originally had the Canvas added to my player object, and wondered if there was something in my player control script that was somehow hiding the canvas, so I have moved the canvas to the empty game object.

This is my code:

public GameObject myCanvasHolder;
// Use this for initialization
void Start ()
{
Debug.Log (myCanvasHolder.ToString() + " is my starting canvas holder.");
myCanvas = myCanvasHolder.gameObject.GetComponent ();
Debug.Log (myCanvas.ToString () + " is my starting canvas");
}

And my logged output is this:

CANVAS_HOLDER (UnityEngine.GameObject) is my starting canvas holder.
null is my starting canvas

UPDATE: I have been able to get it to work by creating a public Canvas and a public Text in my script and directly assigning them to the UI objects in the Inspector. Still not sure why I can’t see these objects with GetComponent though.

Any ideas?

would have to see the scene hierarchy to have any idea

See attached!

Please let me know if you need anything else. I’m confident that there’s just something dumb I’m doing wrong in the implementation of this UI.

Cheers!

2424600--166018--Heirarchy_pic.png

CANVAS_HOLDER is an empty GameObject with no Canvas. if myCanvasHolder is pointing at this then that explains the problem. The Canvas is part of the child GameObject Canvas. Use GetComponentInChildren or assign Canvas to the myCanvasHolder variable**.**

1 Like

OH! The component, Canvas, is a component of the GameObject Canvas, and I was trying to get the canvas component of CANVAS_HOLDER, which doesn’t exist!

Cool, thanks for the clarification!

Cheers!

1 Like