[UNET] OnServerAddPlayer and OnServerRemovePlayer

Hi,

I’m writing a little script where I need to know on the server when a remote client has spawned his/her localPlayer. So I’m using the OnServerAddPlayer method of the NetworkManager class and it’s working correctly. My problem comes when I want to be noticed on the server when the remote client destroys his/her localPlayer prefab. When I’m using OnServerRemovePlayer it is not called by the engine (I tried to log a message). And I precisely need to know when the player prefab has been removed so I can’t use OnServerDisconnect because I need to call an RPC on all my clients otherwise I’ll receive a message like: “Cannot call RPC on … the game object has not been spawned”.

public override void OnServerRemovePlayer (NetworkConnection conn)
    {
        base.OnServerDisconnect (conn);
Debug.Log("NOT CALLED HERE");

        if (numPlayers < playerMinToStart) {
            foreach (GameObject p in GameObject.FindGameObjectsWithTag("Player")) {
                PlayerStatus status = p.GetComponent<PlayerStatus> ();
               
                if (status) {
                    //status.RpcSleep ();
                }
            }
            }
}

Any ideas ?

Thank you in advance.

Put an OnDestroy on the player prefab. Also note that players shouldn’t be destroying their own prefabs - it should come from the server in which case the server could send another Rpc to do something at the same time.

Thank you for your answer,
but when I try to log something in the OnDestory method of the player while checking if I’m on server side I don’t get any message:

void OnDestroy()
    {
        if(isServer)
            Debug.Log ("aegaeg");
    }

I’ve found that isServer check to be horribly unreliable honestly. I set my own boolean when starting the server or client and use that instead.

From the manual:

NetworkBehaviour.isServer - True if this object is running on the server, and has been spawned

NetworkServer.active is true if the server is running.

I found that this field isn’t true until after Awake (always false in Awake) so it seems like the same might be true in OnDestroy