- Home /
When a host player changes his weapon all players get switched to it
I'm making a multiplayer FPS and I just implemented switching weapons. One player acts as a host for the game. When a client switches his weapon it shows properly on all the other clients (and host player), but when the host player switches his weapon, the weapons of all the players switch to target weapon.
Here is my class that performs the weapon switching:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class WeaponManager : NetworkBehaviour {
[SerializeField]
private string weaponLayerName = "Weapon";
[SerializeField]
private AssaultRifleScript primaryWeapon;
[SerializeField]
private Transform weaponHolder;
[SerializeField]
private float weaponSwitchTime = 0.5f;
private Weapons currentWeapon;
private WeaponGraphics currentGraphics;
private int currentWeaponIndex = 1;
public bool isReloading = false;
private void Start()
{
EquipWeapon(new AssaultRifleScript());
}
public void EquipWeapon(Weapons newWeapon)
{
currentWeapon = newWeapon;
GameObject weaponInst = (GameObject)Instantiate(newWeapon.graphics, weaponHolder.position, weaponHolder.rotation);
weaponInst.transform.SetParent(weaponHolder);
currentGraphics = weaponInst.GetComponent<WeaponGraphics>();
if(currentGraphics == null)
{
Debug.LogError("No weapon graphics component on the weapon object: " + weaponInst.name);
}
if(isLocalPlayer)
{
Util.SetLayerRecursive(weaponInst, LayerMask.NameToLayer(weaponLayerName));
}
}
private void ClearOldWeapon()
{
foreach(Transform child in weaponHolder)
{
Destroy(child.gameObject);
}
}
[Command]
public void CmdSwitchWeapon(int selectedWeaponIndex)
{
if (selectedWeaponIndex != currentWeaponIndex)
{
RpcSwitchWeapon(selectedWeaponIndex);
}
}
[ClientRpc]
public void RpcSwitchWeapon(int selectedWeaponIndex)
{
ClearOldWeapon();
switch(selectedWeaponIndex)
{
case 1:
EquipWeapon(new AssaultRifleScript());
break;
case 2:
EquipWeapon(new PistolScript());
break;
case 3:
EquipWeapon(new SniperScript());
break;
case 4:
EquipWeapon(new HeavyScript());
break;
default:
break;
}
currentWeaponIndex = selectedWeaponIndex;
}
}
Could anyone tell me what I'm doing wrong?
Answer by humra · Dec 06, 2017 at 09:47 PM
It turns out to be a silly mistake. All I had to do is add a isLocalPlayer check in another script that actually calls the CmdSwitchWeapons command.
Your answer
Follow this Question
Related Questions
Unity networking tutorial? 6 Answers
Multiplayer projectiles 0 Answers
can firebase real-time database be used on a pc standalone game? 0 Answers
Shoot Projectile Where Camera Faces [PLEASE HELP!] 2 Answers
Photon Networking Instantiating Problem 0 Answers