I’m setting up a UI panel that displays a ton of information, most of which is mapped directly to values in a set of objects. While I started doing it the “default” way, something like this:
public Text playerName;
public Text playerTitle;
public Text playerScore;
public Text playerHealth;
public void SetValues() {
Player player = CharacterManager.Instance.Player;
playerName.text = player.name;
playerTitle.text = player.title;
playerScore.text = player.score.ToString();
playerHealth.text = player.health.ToString();
}
I thought to myself “There has to be a better way.” As it stands, every time a value changes, I need to call SetValues() again on this panel.
There’s the more obvious way of using Update:
private Player player;
public Text playerName;
public Text playerTitle;
public Text playerScore;
public Text playerHealth;
public void Awake() {
player = CharacterManager.Instance.Player;
}
public void Update() {
playerName.text = player.name;
playerTitle.text = player.title;
playerScore.text = player.score.ToString();
playerHealth.text = player.health.ToString();
}
But this seems excessive to be doing every frame.
Soooooo…
I had the idea to use C# events to subscribe UI elements to object properties and have them update themselves only as needed. Ideally this would be done through some sort of utility class so that I could just call it generically like:
public Text playerName;
public Text playerTitle;
public Text playerScore;
public Text playerHealth;
public void Awake() {
Player player = CharacterManager.Instance.Player;
UISubscribe.Subscribe(playerName, player.name);
UISubscribe.Subscribe(playerTitle, player.title);
UISubscribe.Subscribe(playerScore, player.score);
UISubscribe.Subscribe(playerHealth, player.health);
}
And the Subscribe method would take care of converting to string, binding to the events, and setting the text values.
I’ve never worked much with C#'s event system, so I’m not positive what I’m getting myself into. Any advice or pointers are appreciated. In general, though, is this a good idea? Or am I better off throwing it all into Update and calling it a day?