Search code examples
c#unity-game-enginegame-engine

How to: Correctly reference a Text UI component in a script


Working on getting familiar with C# and unity development. Today I am working on getting a reference to a Text UI object in my script. The following code below produces this error:

NullReferenceException: Object reference not set to an instance of an object
handle.Awake () (at Assets/handle.cs:20)

Script looks like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using playPORTAL.Profile;
using UnityEngine.UI;

public class handle : MonoBehaviour
{

    public Text myText;

    // Start is called before the first frame update
    void Start()
    {

    }

    void Awake()
    {
        myText.text = "@organickoala718" ;
    }

    // Update is called once per frame
    void Update()
    {

    }
}

What needs improving to correctly get a reference to the Text UI element?


Solution

  • In general: The same way as with any other Component.

    Either reference it via the Inspector or use GetComponent(Tutorial) or one of its variations.


    So if that Text Component is attached to the same GameObject as your script then you could use GetComponent(API) to get the reference on runtime

    private void Awake ()
    {
        if(!myText) myText = GetComponent<Text>();
        myText.text = "@organickoala718" ;
    }
    

    Also checkout Controlling GameObjects with Components


    Btw you should remove the empty methods Start and Update entirely. They are called by the Unity Engine as messages if they exist so the don't need to exist and only cause unnecessary overhead.