- Home /
The question is answered, right answer was accepted
Is reference better than UnityEvent ?
Actually, I have a UI which updates every time. I want to make it updating only when a player's attribute (like HP) changes. So, I would like to know what is better: give the UI as parameter to a script or just link the UI modification script to an UnityEvent ?
Answer by Jack-Mariani · May 23, 2019 at 12:25 PM
It's much better to not connect UI with update (so using a reference).
Connecting UI with events is much much better, both in terms of performance and encapsulation.
Let me show you also a trick using properties.
public class Health : MonoBehaviour
{
//I'm using Actions because they're (said to) be more performant than UnityEvents, but they are much the same
public Action <int> OnHealthChange;
//track and update health with a property
private int _currentHP;
public int CurrentHP
{
get => _currentHP;
private set
{
_currentHP = value;
OnHealthChange?.Invoke(value);
}
//if you use a property you can be sure that the event will alwaye be called when you change the current hit points
private void SufferDamage(int damage) => CurrentHP -= damage;
private void Heal(int amount) => CurrentHP += amount;
}
}
public class HealthUI : MonoBehaviour
{
public Health _health;
private void ShowHealth(int currentHealth)
{
//show health here, in sliders or tect
}
//start and stop tracking on enable
private void OnEnable()
{
ShowHealth(_health.CurrentHP);
_health.OnHealthChange += ShowHealth;
}
private void OnDisable() { _health.OnHealthChange -= ShowHealth; }
}
Further reading: Difference between UnityEvent and Actions
Thanks for the answer ! I've never thought to use properties for the UnityEvent. It's a very good advice.
Follow this Question
Related Questions
Unity UI: How to stop select event from propagating? 1 Answer
Broadcast mouse event on Canvas 0 Answers
Calling Update() from Pointer Down not working properly 0 Answers
EventSystem not recognizing child objects 0 Answers
Event system or UI Button ? 0 Answers