- Home /
IndexOutOfRangeException: Array index is out of range
I followed a car tutorial put up by bigmisterb (link: http://forum.unity3d.com/threads/86703-Basic-to-Advanced-Car-or-Vehicle-Tutorial) So yeah I followed the trutorial and then applied the code given at the end to the car, but I get this error saying array index is out of range. I have no idea what that means. Specifically, it says
IndexOutOfRangeException: Array index is out of range. CarController.GetCollider (Int32 n)(at Assets/CarController.js:83)
Here is the code. Can anyone help!?
//CarController1.js
var wheels : Transform[];
var enginePower=150.0;
var power=0.0;
var brake=0.0;
var steer=0.0;
var maxSteer=25.0;
function Start(){
rigidbody.centerOfMass=Vector3(0,-0.5,0.3);
}
function Update () {
power=Input.GetAxis("Vertical") * enginePower * Time.deltaTime * 250.0;
steer=Input.GetAxis("Horizontal") * maxSteer;
brake=Input.GetKey("space") ? rigidbody.mass * 0.1: 0.0;
GetCollider(0).steerAngle=steer;
GetCollider(1).steerAngle=steer;
if(brake > 0.0){
GetCollider(0).brakeTorque=brake;
GetCollider(1).brakeTorque=brake;
GetCollider(2).brakeTorque=brake;
GetCollider(3).brakeTorque=brake;
GetCollider(2).motorTorque=0.0;
GetCollider(3).motorTorque=0.0;
} else {
GetCollider(0).brakeTorque=0;
GetCollider(1).brakeTorque=0;
GetCollider(2).brakeTorque=0;
GetCollider(3).brakeTorque=0;
GetCollider(2).motorTorque=power;
GetCollider(3).motorTorque=power;
}
}
function GetCollider(n : int) : WheelCollider{
return wheels[n].gameObject.GetComponent(WheelCollider);
}
Are you sure you have two wheels in your wheels array? Seems like it is either empty or only has one entry; depending on where Unity generates this error (which is difficult to say, since the line numbering is kinda screwed in your code sample ^^)
I assume 'wheels' is being initialized from the inspector? - The error that you're getting means that you're getting out of the array bounds (using an index that is equal to or higher than wheels.length or less than 0) - make sure 'wheels' has 4 or more elements in it.
Answer by Linus · Aug 13, 2013 at 10:37 AM
The error means that n is higher than the number of wheels in the array. If the car has 4 wheels, n should be between 0 and 3. And make sure you have set the values in the inspector.
return wheels[n].gameObject.GetComponent(WheelCollider);
Usually the debug log window will also show what line was calling CarController.GetCollider.
Add a check in your GetCollider function like this:
if(n<wheels.Length)
{
return wheels[n].gameObject.GetComponent(WheelCollider);
}
else
{
Debug.LogError("Wheel index higher than number of wheels");
return null;
}
Please be more specific $$anonymous$$ Gondaliya... a solution to what? I think adding the check mentionned in my previous comment and correctly filling the wheels array is the solution here.