Prevent UI update on every frame in Unity

Unity - prevent UI update on every frame
Difficulty

Let’s prevent UI update on every frame, to improve our Unity game.
When creating a UI within a game, during a level, the first temptation is to put the UI update inside the Update method. This practice is wrong because for most of the time the interface surrounding our game will always be the same. With this tutorial, we will only have to update it in some specific cases. In these cases the player will “recovers” certain upgrades or prizes.

Events to the rescue!

To lighten the load on the Update cycles, we can use a system based on triggers. This thanks to the UnityEvent class, that we will insert within the game manager, so that it is accessible everywhere.

// GameManager.cs
using UnityEngine;
using UnityEngine.Events;

public class GameManager : MonoBehaviour {
    public static UnityEvent RedrawUI = new UnityEvent();
    // ...
}

With this static instance in hand, we perform the redraw every time and only when necessary, by calling it.

On the script that takes care of the UI you can insert a Listener. As the name implies, the listener “listens” for any calls anywhere within our program.
In our case, as an example, we will update the number of doubloons we own. This with each requested interface update, in the OnRedrawUI() method.

// UI.cs
using UnityEngine;
using UnityEngine.UI;

public class UI: MonoBehaviour {
    [SerializeField] private Text doblons;

    void Start() {
        GameManager.RedrawUI.AddListener(OnRedrawUI);
        OnRedrawUI(); // First redraw.
    }

    void OnRedrawUI() {
        doblons.text = GameManager.doblons.ToString();
    }
}

Conclusions for prevent UI update on every frame

Every time our player collects any artefact or coin or loses life points, we update the UI with the following invocation: Invoke().

// ...
// All'interno del metodo che scatena l'aggiornamento dell'interfaccia.
GameManager.doblons += 1;
GameManager.RedrawUI.Invoke();
// ...

This call will fire the listener trigger on the interface script, which will update as desired.

That’s all to prevent UI update on every frame in Unity.
Try it at home!

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

BlogoBay
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.