Is there any effective difference between choosing Awake or OnEnable for hooking up the event handler?
and for detaching it should I use OnDestroy, OnDisable?
Is there any effective difference between choosing Awake or OnEnable for hooking up the event handler?
and for detaching it should I use OnDestroy, OnDisable?
Awake is called when the script is loaded, only once ever.
OnEnable is called any time the script switches from ‘disabled’ to ‘enabled’ and can happen multiple times per game.
I would say Awake is probably better for hooking up events, but there can be exceptions depending on your design.
There are differences.
First of all, all these callbacks are executed at different times of the MonoBehaviour’s lifetime. So it’s possible to use Awake to subscribe to an event that is launched at Start.
Secondly, the callbacks are executed in a different pattern. Start, Awake, and OnDestroy are executed only once. OnEnable and OnDisable can be but might not be executed multiple times.
So, as a rule of thumb: if you use OnEnable to subscribe to an event, you most likely want to use OnDisable to unsubscribe from it. If you use Awake or Start, use OnDestroy instead.