Unity server/client player attachments parenting

Hey

So i have stumbled upon a problem with attaching items or objects to a player on run time over the server and network, the spawning is fine and parent attaching seems to be fine aswell for own player, other network users dont get the parent synchronization somehow.

Example:

  • Player 1 connects, gets a spawned hat on him, when he moves, it moves along, since its parented to head.
  • Player 2 connects, sees the object at current player 1 position and near head, but when Player 1 moves, the hat is not attached/parented.

I’m using unity’s UNET Command attribute to send the object initializiation, instantiation and network server spawning and parent attaching with local positioning. After that, i’m sending a ClientRpc function through to all the clients once, to set the parent for other players aswell, but it seems to be mishandling something or not working correctly.

PS! I know that this code will instantiate and create the hat object for the head parent only for server.

Cmd_AttachItems - Called once the player loads. (Script is attached to player prefab with unityengine.networking use and networkbehaviour set.
Here’s the blank code from my empty example scene:

[Command]
    public void Cmd_AttachItems(string prefabname,Vector3 pos,GameObject parent)
    {
        GameObject spawned_object = Instantiate(Resources.Load(prefabname) as GameObject);
        spawned_object.transform.SetParent(parent.transform);
        Debug.Log(spawned_object.transform.parent.transform);
        spawned_object.transform.localPosition = new Vector3(0,0,0);
        NetworkServer.Spawn(spawned_object);
        Rpc_ClientRpcSyncItemOnce(spawned_object);
    }
    [ClientRpc]
    public void Rpc_ClientRpcSyncItemOnce(GameObject obj)
    {
        Debug.Log(obj.transform.parent.transform);
        obj.transform.SetParent(obj.transform.parent.transform);
        obj.transform.localPosition = new Vector3(0, 0, 0);
    }

I got it fixed!

I made a script that is attached to the attachable item, which has the parent’s net id attached to it.

[SyncVar]
    public NetworkInstanceId parentNetId;

And under the start function of this attachable object i’m attaching the object to the parent with the same net id

if (parentNetId != null) { 
            Debug.Log("Attached item net id:" + parentNetId);
            GameObject parentObject = ClientScene.FindLocalObject(parentNetId);
            transform.SetParent(parentObject.transform);
        }

The player has net id attached to it aswell and once created, the id is sent and set for the attachable item.