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); } }
private void Start() { GameManager.OnLivesChanged += UpdateLivesCounter; } private void UpdateLivesCounter(int lives) { livesCounter.text = lives.ToString(); }
Post a Comment
image video quote pre code