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  *> currentSpeed) {*
  •  						break;*
    
  •  				}*
    
  •  		}*
    
  •  		float gearMinValue = 0.00f;*
    
  •  		float gearMaxValue = 0.00f;*
    
  •  		if (i == 0) {*
    
  •  				gearMinValue = 0;*
    
  •  		} else {*
    
  •  				gearMinValue = gearRatio [i - 1];*
    
  •  		}*
    

gearMaxValue = gearRatio ;*******
* if (started) {*
* float enginePitch = ((currentSpeed - gearMinValue) / (gearMaxValue - gearMinValue)) + 1;*
* audio.volume = 1.0f;*
* audio.pitch = enginePitch;*
* } else {*
* audio.volume = 0f;*
* }*
* }*

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  *> 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 ; // 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
}

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.