using UnityEngine; using UnityEngine.Networking; public class WeaponSwitch : NetworkBehaviour { [SyncVar] public int currentWeapon = 0; private PlayerShooting shootScript; private bool weaponEquipped; [SerializeField] private GameObject weaponHolder; private // Use this for initialization void Start () { shootScript = GetComponent(); } // Update is called once per frame void Update () { GetWeaponInput(); } void GetWeaponInput() { if (!isLocalPlayer) return; SelectWeapon(gameObject.name); int prevWeapon = currentWeapon; if (Input.GetAxis("Mouse ScrollWheel") > 0f) { if (currentWeapon >= weaponHolder.transform.childCount - 1) currentWeapon = 0; else { currentWeapon++; } } if (Input.GetAxis("Mouse ScrollWheel") < 0f) { if (currentWeapon <= 0) currentWeapon = weaponHolder.transform.childCount - 1; else { currentWeapon--; } } if (Input.GetKeyDown(KeyCode.L)) currentWeapon = 0; if (Input.GetKeyDown(KeyCode.Alpha1)) currentWeapon = 1; if (Input.GetKeyDown(KeyCode.Alpha2)) currentWeapon = 2; if (Input.GetKeyDown(KeyCode.Alpha3)) currentWeapon = 3; if (Input.GetKeyDown(KeyCode.Alpha4)) currentWeapon = 4; weaponEquipped = currentWeapon > 0; if (currentWeapon != prevWeapon) SelectWeapon(gameObject.name); shootScript.weaponEquipped = weaponEquipped; } void SelectWeapon(string _playerID) { Player _player = GameManager.GetPlayer(_playerID); Debug.Log("Player ID: " + _player.name); Transform transformsInChild = _player.GetComponentInChildren(); foreach (Transform transformInChild in transformsInChild) { if (transformInChild.name == "_Weapons") weaponHolder = transformInChild.gameObject; } if (weaponHolder != null) { Debug.Log("Looping weapons..."); int i = 0; foreach (Transform weapon in weaponHolder.transform) { if (i == currentWeapon) { Debug.Log(_playerID + " equipping weapon (" + weapon.name + ")"); weapon.gameObject.SetActive(true); CmdSyncWeaponWithRemote(i, _playerID, true); } else { weapon.gameObject.SetActive(false); CmdSyncWeaponWithRemote(i, _playerID, false); } i++; } } } [Command] void CmdSyncWeaponWithRemote(int _weaponID, string _playerID, bool _active) { if (isServer) RpcSyncWeaponWithRemote(_weaponID, _playerID, _active); } /* Bug: Doesnt sync equipped weapon from remote to host, i.e. host player equips a M4 Carbine, the remote will see it, but if a remote equips a weapon, the host will not see it */ [ClientRpc] void RpcSyncWeaponWithRemote(int _weaponID, string _playerID, bool _active) { Player _player = GameManager.GetPlayer(_playerID); Transform transformsInChild = _player.GetComponentInChildren(); foreach (Transform transformInChild in transformsInChild) { if (transformInChild.name == "_Weapons") weaponHolder = transformInChild.gameObject; } weaponHolder.transform.GetChild(_weaponID).gameObject.SetActive(_active); } }