How to subscribe to events in OnEnable when the object that is subscribed to is initialized in Start?

Viewed 65

When using (C#) events in Unity, OnEnable and OnDisable are used to subscribe and unsubscribe to the events, so callbacks won't be triggered on disabled objects. However, sometimes the object that is subscribed to can be initialized only at Start (that is called after OnEnable) which means that when OnEnable is called for the first time, you cannot subscribe to the object as it's not initialized yet (later OnEnables will work fine). One fix for that, as also described here, is to use a flag "hasStarted", so the first time you will subscribe at Start and set it to true, but any other time the object is enabled you will subscribe using OnEnable (making sure that hasStarted is true, that is, it's not the first OnEnable call).

However, that seems really ugly, especially since this situation is not rare at all. And I wonder if there are any other ways to get such a functionality without using a one-time flag.

0 Answers
Related