Search Unity

How do I spawn an object on the server and bind it on the client?

Discussion in 'Multiplayer' started by maikklein, Aug 9, 2015.

  1. maikklein

    maikklein

    Joined:
    Jun 16, 2015
    Posts:
    33
    Code (CSharp):
    1.  
    2.  
    3. public GameObject playerObject;
    4. public Player player;
    5.  
    6. ...
    7. void Spawn()
    8. {
    9.     playerObject = (GameObject)Instantiate(playerPrefab
    10.                                           ,playerPrefab.transform.position
    11.                                           ,playerPrefab.transform.rotation);
    12.     player = playerObject.GetComponent<Player>();
    13.     player.playerController = this;
    14.     NetworkServer.Spawn(playerObject);
    15. }
    16. ...
    17. public override void OnStartServer()
    18. {
    19.      Spawn();
    20. }
    21.  
    22.  
    This code spawns the object correctly on the server and on the client. The problem is that player and playerObject are both null on the client.

    How do I assign the spawned object to the client?
     
  2. maikklein

    maikklein

    Joined:
    Jun 16, 2015
    Posts:
    33
  3. maikklein

    maikklein

    Joined:
    Jun 16, 2015
    Posts:
    33
    Could it be possible that UNet only supports one GameObject per client with the ability to send commands to the server?
     
  4. maikklein

    maikklein

    Joined:
    Jun 16, 2015
    Posts:
    33
    So I was reading though the docs and I found this

    So I gave it a try with

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Networking;
    3. using System.Collections;
    4.  
    5. public class TestNetworkManager : NetworkManager
    6. {
    7.     public GameObject testPrefab;
    8.     public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    9.     {
    10.         GameObject proxyPlayer = (GameObject)Instantiate(playerPrefab,playerPrefab.transform.position,playerPrefab.transform.rotation);
    11.         GameObject test = Instantiate(testPrefab);
    12.         Debug.Log(playerControllerId);
    13.         NetworkServer.AddPlayerForConnection(conn, proxyPlayer, playerControllerId);
    14.         ClientScene.AddPlayer(conn, (short) (playerControllerId + 1));
    15.         NetworkServer.AddPlayerForConnection(conn, test, (short)(playerControllerId + 1));
    16.     }
    17. }
    Which seems to work. Both gameobjects are spawned on the client with isLocalPlayer set to true. I just have to do a bit more work to wire everything correctly on the client and on the server. I will probably do it with

    Code (CSharp):
    1. ClientScene.FindLocalObject(netid);
    Are there any drawbacks with this approach?