Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Access the canvas and its children by code

Discussion in 'UGUI & TextMesh Pro' started by Gabo19x, Dec 24, 2022.

  1. Gabo19x

    Gabo19x

    Joined:
    Oct 23, 2020
    Posts:
    104
    Hello everyone.
    How can I access the Canvas by code?
    Supposedly it is like this:
    Code (CSharp):
    1. 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.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    GetComponent<T>() 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
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,316
    This is the 2D forum, not the UI forum.

    Please look at the available forums before posting. I'll move your post for you.
     
    Gabo19x likes this.
  4. Gabo19x

    Gabo19x

    Joined:
    Oct 23, 2020
    Posts:
    104
    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?
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    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.
     

    Attached Files: