- Home /
"Array out of range" when cycling weapons.
I'm using the mousewheel to cycle through an array of 3 (so far) weapons. on mousewheel up it cycles up through the list, and on mousewheel down it counts down.
This works fine, and prints the weapon currently selected to the terminal.
However, if weapon 3 is selected and the mousewheel pushed up, it throws an exception, "array out of range." Now obviously that's because the variable has increased to 4 and there are only 3 objects in the array, but I can't figure a way to stop it.
Putting the following in my update phase doesn't work:
if (weaponNumber < 0)
{
weaponNumber = weapons.Length;
}
if (weaponNumber > weapons.Length)
{
weaponNumber = 0;
}
I've searched around but can't find a solution. I'm sure it's something really simple I'm missing.
Thanks
Answer by Joyrider · Aug 21, 2013 at 08:18 AM
you should change your second if to
if (weaponNumber >= weapons.Length)
{
weaponNumber = 0;
}
because if you have 3 slots, in an array, numbering start at 0, so 0,1,2. And in your current code, you can still get 3. (which throws the error)
Ha ha, that was even simpler than I had thought!
Ok, I'm half way there. Using $$anonymous$$ouse Wheel Up now correctly cycles through the array changing from the highest back to 0 and so on.
However, cycling down gets stuck at zero. The code:
if (weaponNumber < 0)
{
weaponNumber = weapons.Length;
}
doesn't change the index to the last/highest object in the array, even if I use "weaponNumber <= 0" ins$$anonymous$$d of just "weaponNumber < 0".
On a plus point, it doesn't throw an exception any longer :)
I've played around a bit more and if I manually set it up like this:
if (weaponNumber < 0)
{
weaponNumber = 2;
}
Then it works. Therefore it seems my problem is with setting:
weaponNumber = weapons.Length;
As this is a different problem, I'll post it as a new question.
here you should use
if (weaponNumber < 0)
{
weaponNumber = weapons.Length-1;
}
for the same reason... max id is 2 and your length is 3 (0,1,2)
your last solution works but is not really good. If you add a weapon you need to modify the script.
if (weaponNumber < 0)
{
weaponNumber = weapons.Length - 1;
}
should fix your problem. Remember that an array has length 3 but the last index is 2. So 3 is out of bounds
Understood.
Looks like I need to refresh myself on arrays.
It works perfectly now.
Thankyou for your speedy help.