How to make a dynamic lives counter in optimized way | Unity | C#


How to make a dynamic lives counter in optimized way | Unity | C#


To optimize the performance of your lives counter, you can use events and delegates to handle the changes in the lives variable. Instead of updating the lives counter in the Update method that runs on every frame, you can create methods to increment and decrement the lives variable, and subscribe those methods to events that get triggered when the character hits obstacles or the heart potion.

First, declare a delegate and an event that will handle the changes in the lives variable: public delegate void LivesChanged(int lives);

public delegate void LivesChanged(int lives);
public static event LivesChanged OnLivesChanged;
Then, create methods to increment and decrement the lives variable and trigger the OnLivesChanged event:
public void IncrementLives()
{
    if (lives < maxLives)
    {
        lives++;
        OnLivesChanged?.Invoke(lives);
    }
}

public void DecrementLives()
{
    if (lives > 0)
    {
        lives--;
        OnLivesChanged?.Invoke(lives);
    }
}


Finally, in the script attached to the UI, subscribe to the OnLivesChanged event and update the lives counter only when the event is triggered:
private void Start()
{
    GameManager.OnLivesChanged += UpdateLivesCounter;
}

private void UpdateLivesCounter(int lives)
{
    livesCounter.text = lives.ToString();
}


By using events and delegates, you ensure that the lives counter is updated only when necessary, without affecting the performance of your game. For more information on events and delegates in C#