ServerRpc not called

Hi, I am trying to custom spawn a player in the game by instantiating the player prefab and calling SpawnAsPlayerObject(). I read this has to be done in the server code so I call a ServerRpc function to perform this action.

However, despite all my efforts the ServerRpc function is not getting run. I even set RequireOwnership = false on the function.

This function is in a class that derives from NetworkBehavior. The class is attached to an object in my scene so it is created at runtime before it’s called.

Here is the code. Any clues what I am doing wrong?

public class ServerManager : NetworkBehaviour
{
     public GameObject PlayerPrefab { get; set; }

    [ServerRpc(RequireOwnership = false)]
    public void SpawnPlayerServerRpc(ServerRpcParams serverRpcParams = default)
    {
        Debug.Log("SpawnPlayerServerRpc");
        ulong clientId = serverRpcParams.Receive.SenderClientId;

        GameObject newPlayer = (GameObject)Instantiate(this.PlayerPrefab);
        NetworkObject networkObject = newPlayer.GetComponent<NetworkObject>();
        newPlayer.SetActive(true);
        networkObject.SpawnAsPlayerObject(clientId, true);
    }

    public void SpawnPlayer()
    {
        Debug.Log("SpawnPlayer");
        SpawnPlayerServerRpc();
    }
}

Thank you,
–Mike

Update: I am calling SpawnPlayer() from the host (server). Looks like when the client calls this code it works, but not if the server calls the code.

Is the server not allow to call ServerRPC functions?

Also, side question, why does Debug.Log() called in ServerRPC functions not work?

Hi @Zynpo , ServerRPC are menta to be called from client, and they will execute on the server. (for ClientRPC it’s the opposite).

if you need to be able to call something both from the server and the client, I’d recommend to do:

[ServerRpc(RequireOwnership = false)]
public void SpawnPlayerServerRpc(ServerRpcParams serverRpcParams = default)
{
    OnServerSpawnPlayer();
}

void  OnServerSpawnPlayer() { /* Spawn your player here */ }

And to call SpawnPlayerServerRpc from the client and OnServerSpawnPlayer from the server

Because your ServerRPC is not being executed at all as you’re calling it from the server

Hey @Zynpo did you manage to solve the issue? If yes, what was the cause?

Is this fishnet or netcode? Looks like fishnet to me but don’t know if netcode has same syntax?