Search Unity

Accessing Text properties from an object

Discussion in 'UGUI & TextMesh Pro' started by gussabina, Nov 26, 2016.

  1. gussabina

    gussabina

    Joined:
    Sep 15, 2016
    Posts:
    6
    Hello:

    I'm pretty new to this.
    I created a simple project with a sphere, and I want to attach UI elements (such as texts) and be able to change the text's color and content from a script attached to the sphere gameObject.
    The way it looks in the Hierarchy panel is:
    Sphere
    > Canvas
    > Text

    In the Start() function of the script attached to the Sphere, I tried to do something like this:

    public Text temp;

    void Start()
    {
    .......
    temp = gameObject.GetComponent<Text>();
    temp.text = "Hello";
    }

    But I get NullReferenceException: Object reference not set to an instance of an object.

    How should I modify this code to work?

    Thanks
    Gus
     
  2. gussabina

    gussabina

    Joined:
    Sep 15, 2016
    Posts:
    6
    I forgot to mention that since the Text is defined as public, it appears in the Inspector panel, so I was able to drag&drop the Text gameobject from the Hierarchy to the Inspector. I though this would be enough to give the reference, but it seems it's not the case.

    Thanks
    Gus
     
  3. gussabina

    gussabina

    Joined:
    Sep 15, 2016
    Posts:
    6
    I solved. It basically worked after re-arranging things around.

    Gus
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Just for future reference, you got a null error because of this.
    temp = gameObject.GetComponent<Text>();

    Since you were dragging and dropping text into the public variable in the inspector, this was not needed and was actually creating your null value. This says to look on the same gameobject as the script is attached to and look for a text component, which in your case was not on the same gameobject, so it returned null.