I’m trying to figure out how to do something on the server after an object is destroyed. In my case it’s a connected (networked/spawned) object that should be unspawned and destroyed when the main object is destroyed.
The problem is that inside OnDestroy isServer is already set to false on the server, and OnNetworkDestroy is only called on the client (right?). This means there’s no way to do something specifically when an object is destroyed on the server.
// in a NetworkBehaviour
// this *doesn't* work
void OnDestroy ()
{
if (isServer) // is always false
{
// do something on server
}
}
public override void OnNetworkDestroy ()
{
// do something on client
base.OnNetworkDestroy ();
}
I have some ideas how I could work around it, but I’m curious what’s the “right” way to do that. Either isServer should still be set in OnDestroy or we should have a OnNetworkDestroy function that is called on the client AND on the server.
right, OnNetworkDestroy is only called on clients - including the local client on the host.
And yes, the NetworkIdentity unsets isServer as part of its OnDestroy, so if your script component’s OnDestroy is called after the NetworkIdentity’s OnDestroy then isServer will be false.
Thanks for confirming. Are there any improvements planned in this area? We have OnStartServer and OnStartClient methods, why not OnDestroyServer and OnDestroyClient?
The isServer property is true when the NetworkIdentity for the object is active on the server. If you just want to check if your code is running on the server you could use NetworkServer.active, that is not scoped to a particular object.
ah yeah, that’s true… wasn’t aware that isServer means “is currently spawned and we’re on the server”, thought it’s just a shorthand to check if the script is running on the server.
I don’t understand the use of “OnNetworkDestroy” because it’s not being invoked while stopping the host, neither when disconnecting from server as a client.
It’s just not good enough for cleanup. I’m using regular OnDestroy for now.
just adding to this thread to say this issue tripped me up today.
In my opinion, “isServer” being false on the OnDestroy event should at the least be noted in the official documentation of OnDestroy, and NetworkServer.Destroy. Right now the only way to find this out is to google and find this forum thread.
Even better would be if the behaviour can be fixed, or we can get OnClientDestroy and OnServerDestroy events.