I am updating our app to uNet and I’m having trouble getting my players to spawn.
We have a struct containing several enums, for each body parts. so it could define a player with faceA arms B and feet Z. Reading that structure, we instantiate several prefabs, merge the meshes, and end up with one nice player.
Thing is, spawning that through uNet doesn’t seem to work, as we don’t have a “playerPrefab”. We build the whole thing from the struct we get. I tried generating such a player and then calling AddPlayerForConnection, but from what I understand, clients are then unable to spawn that, since they don’t know about that generated object, and what the server does in only indicate clients which prefab to spawn (it does not serialize the object itself)
So how could one go about generating such a complex thing from a spawn? Is there a way to tell the server look, just send the struct with the spawn data to the clients, and let them generate their own player?
We have a similar scenario, and do something like this:
public class Player : NetworkBehaviour {
[SyncVar] YourStruct spawnData;
[SyncVar] bool hasSpawned;
public override void OnStartAuthority()
{
//Get your spawnData from somewhere
//Tell the server to spawn this player
CmdSpawnMe(spawnData);
}
public override void OnStartClient()
{
//This player may have spawned before this client joined the game, so if that's the case, spawn it now. Otherwise, just wait for the RpcSpawnMe call.
if (hasSpawned)
{
SetUpPlayer();
}
}
[Command]
private void CmdSpawnMe(YourStruct a_data)
{
spawnData = a_data;
SetUpPlayer();
hasSpawned = true;
RpcSpawnMe();
}
[ClientRpc]
private void RpcSpawnMe(YourStruct a_data)
{
//spawnData will be synced by the server automatically,
//but I don't trust it to arrive before this call, so I pass it into
//this function anyway to be sure.
spawnData = a_data;
SetUpPlayer();
}
private void SetUpPlayer()
{
//Build the object with spawnData
}
}
Edit: Forgot to mention: This component is sitting on a (otherwise blank) prefab that’s registered with the NetworkManager, so the clients create that on connecting.
As I see it you should have an empty prefab with NetworkIdentity and a script which has your struct as [SyncVar] and then after spawning you can create the real visual object from the struct and make it the child of the Network prefab and then go on.
Thanks a lot for your help guys, I went with a prefab containing spawn data and a network identity, so when that prefab gets spawned on the client side, they can build their own player model.