Im currently writing a weapon script for a FPS and I want to switch weapons with the mouse wheel. I created an array with the weapons in it and everytime I scroll up with the mouse wheel the index of the weapon increases by one. My problem is that when I'm at the last weapon I get IndexOutOfBounds error message. I've tried to reset the weapon index to 0 if its at the end of the array but for some reason that didn't work. I've also tried to do it with a while loop instead of an if-statement but that didn't work as well. Here's the code:
public class WeaponManager : MonoBehaviour
{
[SerializeField]
private WeaponHandler[] weapons;
private int current_weapon_index;
void Start()
{
current_weapon_index = 0;
weapons[current_weapon_index].gameObject.SetActive(true);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
TurnOnSelectedWeapon(0);
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
TurnOnSelectedWeapon(1);
}
if (Input.GetKeyDown(KeyCode.Alpha3))
{
TurnOnSelectedWeapon(2);
}
if (Input.GetKeyDown(KeyCode.Alpha4))
{
TurnOnSelectedWeapon(3);
}
if (Input.GetKeyDown(KeyCode.Alpha5))
{
TurnOnSelectedWeapon(4);
}
if (Input.GetKeyDown(KeyCode.Alpha6))
{
TurnOnSelectedWeapon(5);
}
if(Input.mouseScrollDelta.y > 0)
{
SwitchToNextWeapon();
}
if (Input.mouseScrollDelta.y < 0)
{
SwitchToPreviousWeapon();
}
}
void TurnOnSelectedWeapon(int weaponIndex)
{
weapons[current_weapon_index].gameObject.SetActive(false);
weapons[weaponIndex].gameObject.SetActive(true);
current_weapon_index = weaponIndex;
}
void SwitchToNextWeapon()
{
weapons[current_weapon_index].gameObject.SetActive(false);
current_weapon_index++;
weapons[current_weapon_index].gameObject.SetActive(true);
if (current_weapon_index >= weapons.Length)
{
current_weapon_index = 0;
}
}
void SwitchToPreviousWeapon()
{
weapons[current_weapon_index].gameObject.SetActive(false);
current_weapon_index--;
weapons[current_weapon_index].gameObject.SetActive(true);
}
}