Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

Dynamic Prefabs in a Multiplayer Game

Discussion in 'Connected Games' started by haroldgeronimo, Dec 3, 2018.

  1. haroldgeronimo


    Oct 12, 2017
    Hello, sorry if my english is bad.
    So I'm currently making an RTS game. There are lots of types of characters so I decided to use scriptable objects to create different types of characters. I also created a base prefab which contains the basic components needed for a character, designed that other components will be added later on instantiation to create the different units. I inserted this base prefab on my NetworkManager as a spawnable prefab.
    I spawn units like this:
    Code (CSharp):
    1. [Command]
    2.     public void CmdSpawnObject (int spawnableObjectIndex, Vector3 position, Quaternion rotation) {
    4.         //gets base prefab
    5.         GameObject go = NetworkManager.singleton.spawnPrefabs[UnitSpawnIndex];
    7.         //gets desired unit scriptable object
    8.         PlayerUnit playerUnit =  unitGroup.units[spawnableObjectIndex];
    10.         //instantiates the base prefab
    11.         go = Instantiate (go, position, rotation);
    13.         //adds components to the base prefab using the sciptable object
    14.         playerUnit.Initialize(go);
    16.         //assigns the unit to the player
    17.         NetworkIdentity ni = go.GetComponent<NetworkIdentity> ();
    18.         NetworkServer.SpawnWithClientAuthority (go, connectionToClient);
    19.         RpcAssignObject (ni, spawnableObjectIndex);
    21.     }
    This creates a problem that only the server has the version of the unit that has the added components. The client on the other hand instantiates only the base prefab.

    Because of this, I tried to also add the needed components using a ClientRpc. This made it so that the unit on the client has the same components. But the when I invoke Commands on the added components this error comes up:


    Thank you to anyone who will help.
  2. dontdiedevelop


    Sep 18, 2018
    Code (CSharp):
    1. NetworkIdentity ni = go.GetComponent<NetworkIdentity> ();
    you're calling networkidentity component in server but clients don't know that component try this
    Code (CSharp):
    1. RpcAssignObject (go, spawnableObjectIndex);
    and in RpcAssignObject get networkidentity component with go.GetComponent<NetworkIdentity>();