Search Unity

Unity 5.1 Networking - Spawn an object as a child for the host and all clients

Discussion in 'Multiplayer' started by james69lemon, Jul 11, 2015.

  1. james69lemon

    james69lemon

    Joined:
    Nov 24, 2013
    Posts:
    6
    I have a player object who can equip multiple weapons. When a weapon is equipped, its transform's parent is set to its hand. I have messed around with this for some time and cannot get this to work for both the host and the client. Right now I am trying to equip the weapon on the server, and tell all the clients to set their parents transforms.

    In the update I am updating the weapons transform

    public NetworkInstanceId weaponNetId;

    [Command]
    void Cmd_EquipWeapon()
    {
    var weaponObject = Instantiate (Resources.Load ("Gun"),
    hand.position,
    Quaternion.Euler (0f, 0f, 0f)) as GameObject;
    weaponObject.transform.parent = hand;
    NetworkServer.Spawn (weaponObject);

    //set equipped weapon
    var weapon = weaponObject.GetComponent<Weapon> () as Weapon;

    weaponNetId = weaponObject.GetComponent<NetworkIdentity> ().netId;
    Rpc_SetParentGameobject (weaponNetId);​
    }

    [ClientRpc]
    public void Rpc_SetParentGameobject(NetworkInstanceId netID)
    {
    weaponNetId = netId;​
    }

    void Update () {

    // set child weapon tranform on clients
    if (!isServer) {
    if (weaponNetId.Value != 0 && !armed) {
    GameObject child = NetworkServer.FindLocalObject (weaponNetId);


    if (child != null) {
    child.transform.parent = hand;
    }​
    }
    }

    I know this isn't the most optimized way to do this..but right now I am just trying to get this to work any way possible and then work on tweaking it. Seems like it should be a simple task.
     
  2. seanr

    seanr

    Unity Technologies

    Joined:
    Sep 22, 2014
    Posts:
    669
    how is it not working?

    btw isServer is true on the host, so the parenting code wont get called on the host. Seems like that check shouldn't be there.
     
  3. KingNate

    KingNate

    Joined:
    Aug 14, 2015
    Posts:
    1
    I'm having a similar issue, sets fine on server but the clients are not updating the parent object, and forgive me if I'm wrong but shouldn't you be using the code below?

    if (child != null) {
    child.transform.SetParent(hand);
    }
     
  4. Jordii

    Jordii

    Joined:
    Sep 14, 2010
    Posts:
    135