1

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);
}
levan
  • 440
  • 1
  • 8
  • 19

2 Answers2

0

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);
}
levan
  • 440
  • 1
  • 8
  • 19
0

Use this to find the parent object:- Transform parentTransform = PhotonView.Find(parentid).gameObject.transform;

And then call the rpc to make the parent object on the client side like this:- this.GetComponent().RPC("RPC_DropObject", RpcTarget.AllBuffered, position, rotation, hasParent, parent.gameObject.GetComponent().ViewID);

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31834213) – Valerij Dobler May 28 '22 at 20:28