[SOLVED] [UNET] How to correctly sync Weapon Switching (Using SetActive()) over network?

Hello!

I have this code to Equip a weapon

  • [Command]
  • void CmdEquipWeapon(int val){
  • RpcEquipWeapon (val);
  • }
  • [ClientRpc]
  • void RpcEquipWeapon(int val){
  • EquipWeapon (val);
  • }
    • void EquipWeapon(int val) {
  • Debug.Log ("Equipping weapons for = " + GetComponent ().Username);
  • if (isReloading) {
  • return;
  • }
  • foreach (GameObject wep in Weapons){
  • wep.SetActive (false);
  • }
  • Weapons [val].SetActive (true);
  • WeaponNameText.text = Weapons [val].transform.name;
  • weapon = WeaponHolderObject.GetComponentInChildren ();
  • GetComponent ().leftHandTransform = weapon.gameObject.transform;
  • WeaponHUD.sprite = weapon.HUD;

}

This works perfectly when im switching weapons on the client , it gets synced across network But when i switch weapons on the Server (Host) , It switches the weapons of all clients on the server And the debug message is thrown on all the clients , saying they changed their own weapons ;_;

What am i doing wrong?

Please help TIA :slight_smile:

You’re transmitting Rpc to ALL objects that can receive that Rpc.
With that in mind I would’ve used the following - [TargetRpc] attribute, to send only to the player that requested that command. Use connectionToClient for that.

Another alternative is to write a custom NetworkMessage handler, if you prefer LLAPI.
You can always go with a pleb way of doing this - checking isLocalPlayer. Although, in my opinion, this approach is far beyond inefficient.

Also, try to use code tag for pasting code in the future.

Use a islocalplayercheck before calling the command. Like this:

if(islocalplayer)
{
      CmdEquipWeapon(val);
}

I hope this works for you!

Hey Thanks for your reply
Can you please tell me more about it? im kind of a beginner :stuck_out_tongue:
I tried using TargetRpc and connectionToClient , but i think connectionToClient is null and it didnt sync with anything

Thanks for you reply
Unfortunately , i have already tried it and it seems to make no change , what it just did is not update it on the Server but it did the weapon changing on all clients

All you have to do is this:
Make a syncvar of the color.
On the hook method, apply the syncvar value and then apply the value to the flag.
And then during initalization, also apply the color.
And then before you spawn the object over the network. Just set the syncvar on the SERVER instance. (from Server Code)

Thanks for your reply
I got it fixed finally , what i did is just disabled the Weapon script on other clients except mine and it works now !

Finally Fixed it
I just had to disable the equipping script on the other clients except the local player and its works fine now
Thanks community

1 Like