- Home /
Question about unsubscribing eventhandlers OnDisable and OnEnable
Hi! this is a pretty straightfroward question
I use events on various places of my AI scripts, and i have read that event subcription and unsubcription must be done in OnEnable and OnDisable respectively, wich works well enough but since im using pooling for my AI's OnEnable and OnDisable will be called more than 1 time, and sometimes, 10 enemies will get enabled at the same time, therefore making 10 calls to OnEnable.
All this make me ask, how heavy really is subscribing to events? i need to keep this into account, since my AI will spawn from my pool, and will get disable and enabled multiple times, and i was thinking, maybe instead of OnEnable and OnDisable i should use Awake and OnDestroy, since these will get called only once, so no matter how many times my Ai's get enabled and disabled, the event subscription will get called only once, but then comes out the question of memory leaks, what do you think?
In summary :
-Are OnEnable and OnDisable really the best place to subscribe and unsubscribe?
-Would Awake and OnDestroy also work?
-How performance and CG heavy is event subscription and unsubcription?
Answer by RakshithAnand · Apr 26, 2016 at 11:31 AM
@LunaTrap Yes it is the best place. If you subscribe to an event in Awake, then the event handlers will still be called when the gameobject is disabled. Hence its better to unsubscribe it in OnDisable
Yes Awake and Destroy would still work but handlers are still executed if disabled as said above.
Events are fast and the thing you need to worry about is, you have to unsubscribe at some point in time else events will hold a reference even if objects are destroyed.
I see, then i guess i need to suck up the small hit on performance and memory allocations, thanks a lot
Answer by ben-rasooli · Apr 26, 2016 at 01:11 PM
There is no rule where to unsubscribe your eventHandler, you should unsubscribe whenever you're done with it. It can be even in a simple function. If you don't have many objects in your pooling system which use the same handler, or if you know you're gonna subscribe to it again soon, then just leave it there stay on the object.
This is in my opinion a more appropriate answer. OnDestroy/OnDisable are only appropriate if they are the right moment to unregister. There are cases when you unregister in the listening method so that it happens only once. OnEnable is right if OnDIsable is used, or it will pile up listeners. It is all a matter of personal design in the end.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Regarding Update() Performance 0 Answers
System or Unity Action? 1 Answer
How do Delegates and Events work? 1 Answer
Stack Overflow error on delegate call 2 Answers