OnStart/StopServer or Start/OnDestroy for subscribing/unsubscribing to Actions?

In this lecture, the pattern of subscribing to Actions is well demonstrated, however I noticed that sometimes the subscription/unsubscription is done in OnStartServer / OnStopServer, and other times it is done in Start / OnDestroy instead. Is there a best-practice or rule-of-thumb to apply to determine which pair is best to use for any given component?

It all depends on your needs.

If you need it when the server starts/ends, then OnStartServer / OnStopServer works better.

If you’re using on a non pooled object, Start / OnDestroy may be best.

If you’re pooling an object, OnEnable / OnDisabe may be best.

Would there be any disadvantage to using OnEnable / OnDisable instead of Start / OnDestroy all times (except when syncing with the Server)? I’m used to setting and clearing callbacks / events etc in OnEnable and OnDisable for other things, so it feels cleaner to me to do that, especially since OnDestroy is the dual of Awake not Start which messes with my OCD…

If you have an object that is disabled and enabled and has call backs, if you only do it in start/destroy it can be the source of unanticipated bugs.

Most of the time it doesn’t matter. Other times, it can cause a race condition.

It’s good to learn when each of them happens and use the one that is most appropriate to the situation at hand. OnEnable, Start and Awake all happen at different times. Doing it one way regardless of the circumstance can paint you into the preverbial corner.

This situation gets even more complicated for multiplayer, because sometimes we are reliant on the network connection to subscribe/unsubscribe from events. As well the event handlers themselves may rely on the network connection.

For example you don’t want to call an event that relies on the network connection in Start(), if the connection won’t be setup until OnStartServer().

Really, this is just a case by case situation. I know we had a case in this course where an object was getting destroyed before it’s server connection was broken. The solution was to subscribe to an event in OnStartServer, but then unsubscribe to in during OnDestroy.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms