I’ve been struggling a lot lately with adding players to an existing server.
Here is the code snippets I’m using. When a new player spawns, it’s as if the server has been the owner of that player from the start.
[SerializeField] private GameObject playerPrefab;
private void Singleton_OnClientConnectedCallback(ulong obj) {
SpawnPlayerServerRpc(playerPrefab, obj);
}
[ServerRpc]
private static void SpawnPlayerServerRpc(GameObject playerPrefab, ulong clientID, ServerRpcParams serverRpcParams = default) {
GameObject playerTransform = Instantiate(playerPrefab);
playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(serverRpcParams.Receive.SenderClientId, true);
}
Ralphp
2
You need to pass that ulong client ID from OnClientConnectedCallback to SpawnAsPlayerObject. This is the ID of the client that has just connected.
What you’re currently doing is passing the client ID from the caller of the RPC, which doesn’t make any sense here.
But instead of making a ServerRPC, I would listen to the OnClientConnectedCallback on the server, and spawn the player object directly, like:
[SerializeField] private GameObject playerPrefab;
private void Singleton_OnClientConnectedCallback(ulong newClientId) {
if(!IsServer) return;
GameObject playerTransform = Instantiate(playerPrefab);
playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(newClientId, true);
}
Is there any way to do this in which each player that connects has their unique player instantiated?