Events and unsubscriptions

Hi,

I have a basic question. Why do we unsubscribe for functions?

As far as I understand if we call health.ServerOnDie += ServerHandleOnDie;
server calles the method which destroys our object (so it is destroyed at all clients PC’s and on server), - this is understandable for me, but why do we call unsubsribe method? It cannot be destroyed twice, because function was already done so the instance does not exist.

Or cannot we just call in one place OnStopServer - unsubsribe all methods?

Is it a need or just fo keeping things clear?

PS. I am not sure if understand OnServerStop - is it when we pause the game ? I could not find it in mirror docs.

Hi,

" OnStopServer()

This is called when a server is stopped - including when a host is stopped."
https://mirror-networking.com/docs/api/Mirror.NetworkManager.html

It’s a good habit to unsubscribe to from the events when they are no longer needed. In this project there have been several bugs that have occurred because an object is destroyed before it can unsubscribe in OnServerStop(). The result is that later it gets subscribed to the event twice and calls the method twice.

I’m not quite sure how C# events work with destroyed objects, but clearly it is a bit messy and it’s a good idea to clean up after oneself.

Thanks, I think it solves my doubts.

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

Privacy & Terms