Hello everyone,
I’m developing a turn-based game where I use a Singleton for my Turn System (it seemed logical).
Now when this TurnManager starts a new turn, it fires an event so that everything that needs to do something specific at turn start can be aware it’s a new turn and do their things.
So in my TurnManager I have :
public event Action OnStartTurn;
private void Awake() {
if (Instance != null && Instance != this) {
Destroy(this);
} else {
Instance = this;
}
}
public void NewTurn() {
OnStartTurn.Invoke();
}
And on an GameObject Unit I want to subscribe :
private void OnEnable() {
TurnManager.Instance.OnStartTurn += DoStuff;
}
My problem here is that on execution, it does a nullreference exception because the OnEnable of Unit is called before the Awake of TurnManager.
The simple fix is to subscribe to the event in the Start function of Unit instead of OnEnable. But I’m not sure if it feels right or if I’m on a wrong path allover.
I’ve always seen and used OnEnable and OnDisable to subscribe / unsubscribe to events. But I’m quite new to using Singletons and it’s the 1st time I’m firing an event from a Singleton.
I’ve searched the web but events and singleton are always opposed as design patterns. Though here, I feel like it makes sense that my TurnManager is a Singleton, and I think it makes sense too to alert everyone that a new turn has started through an event. Am I missing something here why Singleton and Events shouls not be used together ? Or is it something normal, as is to use Start instead of OnEnable to susbscribe to that event.
Thanks in advance to anyone who will share their insights with me or point the flaws and stupidities of my approach. I’m here to learn.