//Called on server.
//This allows customization of the creation of the GamePlayer object on the server.
//By default the gamePlayerPrefab is used to create the game-player, but this function allows that behaviour
//to be customized.The object returned from the function will be used to replace the lobby-player on the connection.
public override GameObject OnLobbyServerCreateGamePlayer(NetworkConnection conn, short playerControllerId)
{
//default player prefab index
int prefabIndex = 1;
//For each lobby player in scene
foreach (LobbyPlayer lp in FindObjectsOfType<LobbyPlayer>())
{
//If connection contains lobby player network identity
if (conn.clientOwnedObjects.Contains(lp.GetComponent<NetworkIdentity>().netId))
{
//then set prefab index to spawn value
prefabIndex = lp.spawnTypeValue;
}
}
//Spawn game object from spawn list
GameObject playerPrefab = Instantiate(spawnPrefabs[prefabIndex]);
return playerPrefab;
}
This works fine when I test he game with one player. When there is two players it tells me that conn.clientOwnedObjects is null. Is there a better way to find the lobby player on the server that is used by that specific connection?
After doing some research I figured out how to do this. For anyone else trying to do something similar this worked for me.
//Called on server.
//This allows customization of the creation of the GamePlayer object on the server.
//By default the gamePlayerPrefab is used to create the game-player, but this function allows that behaviour
//to be customized.The object returned from the function will be used to replace the lobby-player on the connection.
public override GameObject OnLobbyServerCreateGamePlayer(NetworkConnection conn, short playerControllerId)
{
//default player prefab index
int prefabIndex = 1;
//For each lobby player in scene
foreach (LobbyPlayer lp in FindObjectsOfType<LobbyPlayer>())
{
int connectionID = 0;
NetworkIdentity ni = lp.GetComponent<NetworkIdentity>();
//Get connection id from network identity.
//The connection id value depends on whether its a client player or server player
if (ni.connectionToClient != null)
connectionID = ni.connectionToClient.connectionId;
else if (ni.connectionToServer != null)
connectionID = ni.connectionToServer.connectionId;
//If connection id on lobby player is same as connection id
if (connectionID == conn.connectionId)
{
//then set prefab index to spawn value
prefabIndex = lp.spawnTypeValue;
}
}
//Spawn game object from spawn list
GameObject playerPrefab = Instantiate(spawnPrefabs[prefabIndex]);
return playerPrefab;
}