- Home /
The question is answered, right answer was accepted
Array index is out of range - Why?
I've put stars next to the line that causes it. Can anybody spot the problem?
public int[] gearRatio = new int[0];
void EngineSound ()
{
int gears = gearRatio.Length;
int i;
for (i = 0; i < gears; i++) {
if (gearRatio [i] > currentSpeed) {
break;
}
}
float gearMinValue = 0.00f;
float gearMaxValue = 0.00f;
if (i == 0) {
gearMinValue = 0;
} else {
gearMinValue = gearRatio [i - 1];
}
gearMaxValue = gearRatio [i];*******
if (started) {
float enginePitch = ((currentSpeed - gearMinValue) / (gearMaxValue - gearMinValue)) + 1;
audio.volume = 1.0f;
audio.pitch = enginePitch;
} else {
audio.volume = 0f;
}
}
Answer by Bonfire-Boy · Feb 13, 2015 at 11:23 AM
Following the for loop starting at line 7, i can be >=gears (because that's the condition for ending the loop).
But gears is set to the length of your array, so the largest value you can use to index into the array is (gears-1). So using i to index into it when i>= gears will cause that error.
It's not clear what you're trying to do here, maybe something like this though...? Note in particular that if i comes out of the loop because it breaks the < gears condition, then it will be too large to use to access elements of the array. But you should also check that the array has >0 elements in case you forget to set it up in the inspector or from another function.
for (i = 0; i < gears; i++)
{
if (gearRatio [i] > currentSpeed)
{
break;
}
}
float gearMinValue = 0.00f;
float gearMaxValue = 0.00f;
if (i == 0)
{
gearMinValue = 0; // this is actually redundant but I've followed your code for clarity
}
else
{
gearMinValue = gearRatio [i]; // lowest gear for speed
}
if (gears > 0) // check that the array contains some elements before trying to access the last one
{
gearMaxValue = gearRatio [gears-1]; // highest possible gear
}
Thanks for your answer, but what would be the solution? I can't work it out from your answer. :(
It's not clear exactly what you're trying to do but I've added a possible solution.
It boils down to making sure a) that the array isn't empty and b) the index you're using isn't too large for the array's length, before trying to access an element of the array
Answer by Leslie-Young · Feb 13, 2015 at 11:41 AM
Add at top of the EngineSound() function the following ..
if (gearRatio.Length == 0) return;
This will cause the function to not execute until your gearRatio array is set up correctly.
You are entering the function while gearRatio is not filled out. I'm guessing you are supposed to add some values via the Inspector.
Follow this Question
Related Questions
Engine Sound & Turbo 0 Answers
What is your solution? (Zombie Sounds) 1 Answer
Buggy Engine Sound (pitch) 0 Answers
Help with sound clips [C#] 0 Answers
Multiple Cars not working 1 Answer