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 ?
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