Spawning and parenting (weapon)

Hello good people!

I’m fumbling my way though a small top down LAN shooter but are in need of advice.
I wish to spawn weapons and parent them to the characters hand. I’ve made/found some code to test with a cube …

[Command]
    void CmdCube() {
        Debug.Log(gameObject);
        GameObject inst = Instantiate(cube, transform.position, transform.rotation) as GameObject;
        NetworkServer.Spawn(inst);
        RpcSetParent(inst, gameObject);
    }

    [ClientRpc]
    void RpcSetParent(GameObject obj, GameObject parent) {
        obj.transform.parent = parent.transform;
    }

Cube spawns fine on all clients and host. All client cubes a parented correctly on host. The client however does not parent the hosts cube correctly. Creating a second client is even more funky! Second seems to update correctly in the first client, but first not correctly in second.

I hope this makes sense =D

It seems to come down to “when” the objects are instantiated and parented. I was calling the function from “OnStartLocalPlayer()”, as to create a default weapon on start. However as the host starts before the clients are connected its parenting [ClientRpc] call falls on deaf ears (apart from itself). Once clients connects they have no idea and thus the hosts object remain unparented on their side.

Any suggestions? =D

If they object being spawned doesn’t need network behaviour, I’d use sync-vars to hold reference/flags to what has been spawned/attached. In the clients OnStartClient, all those syncvars are set, ready to go and you can use them for initial setup. Then use Command/ClientRPC for “normal” operations. You could use syncvar’s hook method, but an actual rpc function which takes params is easier… YMMV, this was a very complex issue for us in our game, and we had tonnes of timing issues we had to solve for, as our objects were network aware…

1 Like

Thanks a lot for the reply Jos-Yule =D.
I will try and batch something together, hopefully this weekend.

Thanks man!