Access the canvas and its children by code

Hello everyone.
How can I access the Canvas by code?
Supposedly it is like this:

canvas = GetComponent<Canvas>();

But it’s not working. Error:
There is no ‘Canvas’ attached to the “NaveJugadorRojo” game object, but a script is trying to access it.
You probably need to add a Canvas to the game object “NaveJugadorRojo”. Or your script needs to check if the component is attached before using it.

And also how can I access, for example, a text by code.
I didn’t find anything useful in the documentation or in other forums.

GetComponent() works in two ways:

The way you do it above, it only looks where this script is located.

The other way is if you have a GameObject or other Component variable, you can use that:

myGameObject.GetComponent<T>()

Until you build more confidence using the Unity API, I highly recommend NOT getting stuff by code. Just drag it into a public field.

More generally, it is just the same answer again and again:

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

This is the 2D forum, not the UI forum.

Please look at the available forums before posting. I’ll move your post for you.

1 Like

I have to use it and get it by code, since the object that needs it is created during the game and you have to add those components to it. Is there another way to assign the Canvas and other UI elements other than by code?

Yes, drag it in like any other item.

If you have a dynamic number of things, make a template for the item(s) and then copy them.

But author the dragged-in fields in the editor. See a dynamic content example enclosed.

8723331–1179720–DynamicUIDemo.unitypackage (96.1 KB)