IndexOutOfRangeException:数组索引超出范围

时间:2015-02-02 20:11:25

标签: javascript arrays

我不明白这个错误是什么原因,任何人都可以帮助我吗?

IndexOutOfRangeException: Array index is out of range. (at Assets/Scripts/PlayerCar.js:73) CompareApproximately (det, 1.0F, .005f) UnityEditor.DockArea:OnGUI()

我的代码:

var GearRatio : float [ ];
var CurrentGear :int= 1;
var EngineTorque:float=230.0;
var MaxEngineRPM:float=3000;
var MinEngineRPM:float=1000;
private var EngineRPM: float = 0.0;

function Start () { 
        rigidbody.centerOfMass += Vector3(0, -1f, 0.25f);
}
function Update () {
        EngineRPM =( FrontLeftWhell.rpm + FrontRightWhell.rpm)/2 * GearRatio[CurrentGear];
        ShiftGears();

        FrontLeftWhell.motorTorque = (EngineTorque /GearRatio[CurrentGear]) * motorInputTouch;
        FrontRightWhell.motorTorque = (EngineTorque /GearRatio[CurrentGear]) *  motorInputTouch;        
}

function ShiftGears(){

        if(EngineRPM>=MaxEngineRPM){
        var AppropriateGear: int =CurrentGear;
        for (var i=0;i<GearRatio.length;i++){
                if(FrontLeftWhell.rpm * GearRatio[i]>MaxEngineRPM){
                    AppropriateGear=i;
                    break;
                }
            }
        CurrentGear=AppropriateGear;
}

if(EngineRPM <=MinEngineRPM){
    AppropriateGear=CurrentGear;
    for (var j=0;j<GearRatio.length;j++){
        if(FrontLeftWhell.rpm * GearRatio[i]>MinEngineRPM){
            AppropriateGear=j;
            break;
        }
    }
   CurrentGear=AppropriateGear;
}

2 个答案:

答案 0 :(得分:1)

我认为,问题只是这一行

EngineRPM =(FrontLeftWhell.rpm + FrontRightWhell.rpm)/ 2 * GearRatio [CurrentGear];

    FrontLeftWhell.motorTorque = (EngineTorque /GearRatio[CurrentGear]) * motorInputTouch;
    FrontRightWhell.motorTorque = (EngineTorque /GearRatio[CurrentGear]) *  motorInputTouch; 

答案 1 :(得分:0)

查看ShiftGears函数中的最后一个if语句:

if(FrontLeftWhell.rpm * GearRatio[i]>MinEngineRPM){

您的循环使用j作为当前索引,但您使用i来访问GearRatio数组。请改用j