using UnityEngine; using UnityEngine.UI; public class WeaponSwitcher : MonoBehaviour { public Weapon[] weapons; public int currentIndex; public Text weaponNameText; public WeaponHUD hud; private void Start() { if (weapons == null || weapons.Length == 0) return; for (int i = 0; i < weapons.Length; i++) { if (weapons[i] == null) continue; weapons[i].Initialize(); weapons[i].gameObject.SetActive(false); } currentIndex = Mathf.Clamp(currentIndex, 0, weapons.Length - 1); SwitchTo(currentIndex); } private void Update() { if (weapons == null || weapons.Length == 0) return; if (Input.GetKeyDown(KeyCode.Alpha1)) SwitchTo(0); else if (Input.GetKeyDown(KeyCode.Alpha2)) SwitchTo(1); else if (Input.GetKeyDown(KeyCode.Alpha3)) SwitchTo(2); float scroll = Input.GetAxis("Mouse ScrollWheel"); if (scroll > 0.01f) NextWeapon(); else if (scroll < -0.01f) PreviousWeapon(); } public void SwitchTo(int index) { if (weapons == null || weapons.Length == 0 || index < 0 || index >= weapons.Length) return; // Reloading locks weapon switching to keep ammo state predictable. Weapon currentWeapon = GetCurrentWeapon(); if (currentWeapon != null && currentWeapon.IsReloading()) { if (hud != null) hud.ShowMessage("Cannot switch while reloading."); return; } for (int i = 0; i < weapons.Length; i++) { if (weapons[i] == null) continue; bool active = i == index; if (!active && weapons[i].gameObject.activeSelf) weapons[i].OnDeselected(); weapons[i].gameObject.SetActive(active); } currentIndex = index; Weapon selected = GetCurrentWeapon(); if (selected != null) { selected.OnSelected(); if (weaponNameText != null && selected.data != null) weaponNameText.text = "Weapon: " + selected.data.weaponName; if (hud != null) hud.SetWeapon(selected.data); } } public void NextWeapon() { if (weapons == null || weapons.Length == 0) return; SwitchTo((currentIndex + 1) % weapons.Length); } public void PreviousWeapon() { if (weapons == null || weapons.Length == 0) return; int nextIndex = currentIndex - 1; if (nextIndex < 0) nextIndex = weapons.Length - 1; SwitchTo(nextIndex); } public Weapon GetCurrentWeapon() { if (weapons == null || weapons.Length == 0 || currentIndex < 0 || currentIndex >= weapons.Length) return null; return weapons[currentIndex]; } }