1
votes

So I spawn players and than guns that they have, on a host it works perfectly but on a client guns do not become instance of an object. Here's the code

 [Command]
 void CmdSpawn() {
     gun = (GameObject)Instantiate(gunToEquip, weaponPosition.position, weaponPosition.rotation);

     NetworkServer.SpawnWithClientAuthority(gun, connectionToClient);
     gun.transform.parent = weaponPosition;
 }
2

2 Answers

2
votes

First of all, you aren't setting the parent on client. Only on the server. The host is server and client at the same time so it works. Second - have you dragged a gun prefab into network manager's spawnable prefabs slot?

Also, I believe you shouldn't be doing it like so:

gun.transform.parent = weaponPosition;

Use that instead:

gun.transform.SetParent(weaponPosition);

Try that:

[Command]
void CmdSpawn() 
{
    gun=(GameObject)Instantiate(gunToEquip,weaponPosition.position,weaponPosition.rotation);
    gun.transform.SetParent(weaponPosition);
    RpcSpawn();
}

[ClientRpc]
void RpcSpawn()
{
    if(NetworkServer.active) return;
    gun = (GameObject)Instantiate(gunToEquip, weaponPosition.position, weaponPosition.rotation);
    gun.transform.SetParent(weaponPosition);
}
2
votes

It seems to be a duplicate of Unity 5.1 Networking - Spawn an object as a child for the host and all clients

The idea discussed there is to synchronize network ID of the parent object, e.g. on the Server side while spawning:

var gun = Instantiate (...);
gun.parentNetId = this.netId;
NetworkServer.Spawn (gun);

And later on the clients:

// GunController.cs
[SyncVar]
public NetworkInstanceId parentNetId;

public override void OnStartClient()
{
    GameObject parentObject = ClientScene.FindLocalObject(parentNetId);
    transform.SetParent(parentObject.transform);
}