Prevent UI update on every frame in Unity

Unity - prevent UI update on every frame
Difficulty

Let’s prevent UI update on every frame.
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 and it will only have to be updated in some specific cases in which the player “recovers” certain upgrades or prizes.

Events to the rescue!

To lighten the load on the Update cycles, a system based on triggers can be used, thanks to the UnityEvent class, to be inserted 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 the redraw can be performed every time and only when necessary, by calling it.

On the script that takes care of the UI you can insert a Listener which, as the name implies, listens for any calls anywhere within our program.
In our case, as an example, the number of doubloons owned will be updated 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, the UI can be updated 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.