Signup/Sign In

Unity 3D: Update UI Elements on Canvas in Realtime

In the last tutorial we learned how we can add a Text label UI Element to our Game canvas.

We could have easily done that by just importing a sprite, right? Why did we bother making a Canvas? One of the major reasons is because we want to have the option of being able to modify the text, counters and images using a script. In fact, let's try that out!

Clear the Text Field from the Text gameObject, so that it doesn't say anything.

Text UI element with empty text field

Create a new script called ScoreBehavior and open it up.

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

public class ScoreBehaviour : MonoBehaviour
{
    private Text thisText;
    private int score;
    
    void Start()
    {
        thisText = GetComponent<Text>();
        
        // set score value to be zero
        score = 0;
    }
    
    void Update() 
    {
        // When P is hit
        if(Input.GetKeyDown(KeyCode.P))
        {
            // add 500 points to score
            score += 500;
        }
        // update text of Text element
        thisText.text = "Score is " + score;
    }

}

NOTE: Line number 4 is quite an important code line here. Your IDE will give you a Missing Reference error if you forget to include any resource/class/package that you are using in your code, using the using directive.

So what else are we doing here? First of all, we're initializing a Text class variable with the name thisText. The Text class is available only if you add the using UnityEngine.UI at the top, since this class is part of UnityEngine.UI package.

In the Start() function, you'll see recognizable statements, nothing out of the ordinary. The first statement, assigns the thisText variable to the Text component attached to the gameObject, and the other simply sets the score to 0 initially.

In the Update() method, we define an input control to add 500 points to the score each time we press the P key.

Now, the Text class has a text property, which is stored as a string, and this value is what that instance will actually show in the game. In fact, you're setting the Text.text property to a value each time you type in something in the text field in the Inspector view. What we're doing is updating the text value of our thisText object in each frame.

Save this script, and head back to Unity. The label seems to have disappeared, but when you run the game.

Adding UI Elements


Press P a few times, and you should see the score update!

Adding UI Elements


Updating the Text UI Element from other scripts

You can extend this concept by adding a public static method to your script, and calling them from other Behaviour scripts.


What is static keyword for?

The keyword static makes a method or variable maintain a state till the end. It can be called in other classes by using the class name in which the static method is defined.

Also, only static variables can be used inside a static method.

This is generally a universal concept which stands true in case of Java, C# etc programming languages.

Our class ScoreBehaviour will look like:

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

public class ScoreBehaviour : MonoBehaviour
{
    private Text thisText;
    private static int score;
    
    void Start()
    {
        thisText = GetComponent<Text>();
        
        // set score value to be zero
        score = 0;
    }
    
    void Update() 
    {
        // update text of Text element
        thisText.text = "Score is " + score;
    }
    
    // adding a new method to our class
    public static void AddScore()
    {
        // add 500 points to score
        score += 500;
    }

}

If you remember, in the tutorial where we captured the collision of fireball with the target, we defined a class TargetBehaviour which had a OnCollisionEnter2D method defined. Let's update that method to update the score whenever the bullet hits the target.

public class TargetBehaviour : MonoBehaviour
{
    
    void onCollisionEnter2D(Collision2D col) 
    {
        // When target is hit
        if(col.gameObject.tag == "Bullet")
        {
            Debug.Log("Target was Hit!");
            
            // calling AddScore method
            ScoreBehaviour.AddScore();
            
            Destroy(col.gameObject);
            Destroy(gameObject);
        }
    }

}

This code will now change the score by 500 each time you hit the target. Create a few duplicates of the target gameObject and try it out.

Updating the Text UI Element from other scripts

Updating the Text UI Element from other scripts


Wonderful. Of course, there is much more to the UI system than simply making static or dynamic text. You can add images, sliders, buttons and a lot of familiar UI elements by using this method. We urge you to try and explore these elements and figure out how they work, both in the Editor and in scripting.