I am writing a simple multiplayer board game in Unity.
I have the following problem: transport.setparent() not working on a client side. When I launch a game as a server, everything is OK. When I connect to the server as a client transform.setParent() does nothing.
Here is my code:
public GameObject PlayerPrefab;
private GameObject player;
// Use this for initialization
void Start () {
if (!isLocalPlayer)
{
return;
}
Debug.Log("Spawning.");
CmdSpawn();
}
[Command]
void CmdSpawn()
{
player = Instantiate(PlayerPrefab);
NetworkServer.SpawnWithClientAuthority(player, connectionToClient);
player.transform.SetParent(GameObject.Find("BoardPanel").transform, false);
}
I have found the answer. Here is my solution: Step 1) Use a SyncVar to synchronise the netID of the parent object between the server and client. Step 2) When the object is spawned on the client, find the parent using the synchronised netID and set it as your transform's parent.
[Command]
void CmdSpawn()
{
Debug.Log("Spawning.");
player = Instantiate(PlayerPrefab);
player.GetComponent<Player>().ParentNetId = this.netId;
NetworkServer.SpawnWithClientAuthority(player, connectionToClient);
}
And need to add this code in a Player script:
[SyncVar]
public NetworkInstanceId ParentNetId;
public override void OnStartClient()
{
Debug.Log("OnStartClient.");
transform.SetParent(GameObject.Find("BoardPanel").transform, false);
}