如何解决IndexOutOfRangeException?

时间:2015-09-27 09:52:47

标签: unity3d unityscript

我有一些与IndexOutOfRangeException相关的错误。错误次数超过200次,当我玩游戏时出现错误。

错误显示如下:

  

IndexOutOfRangeException:数组索引超出范围。 GameController.OnGUI()(在Assets / MicroRacers Assets / Scripts / GameController.js:67)

这是我的游戏控制器的代码。

var CheckPoints:Transform[];

var LapsToWin:int = 5;
var PointsPerPlace:Array = new Array(8,4,2,1);

var CountDownToStart:float = 5;

var Items:Transform[];
var ItemCopy:Object;
var SpawnTime:Vector2 = Vector2(5,10);
private var SpawnTimeCount:float = 0;
var MaximumItems:int = 5;
private var ItemCount:int = 0;

private var FinishPlace:int = 0;

private var Players:int = 1;
var RaceEndDelay:float = 5;

//~ function Awake()
//~ {
    //~ Application.targetFrameRate = 30;
//~ }

function Start()
{
    SpawnTimeCount = Random.Range(SpawnTime.x, SpawnTime.y);
}

function Update () 
{
    if ( SpawnTimeCount > 0 )
    {
        SpawnTimeCount -= Time.deltaTime;
    }
    else if ( ItemCount < MaximumItems )
    {
        SpawnTimeCount = Random.Range(SpawnTime.x, SpawnTime.y);
        ItemCount++;

        ItemCopy = Instantiate(Items[Mathf.Floor(Random.Range(0, Items.length - 1))], CheckPoints[Mathf.Floor(Random.Range(0, CheckPoints.length - 1))].position + Vector3.up * 0.3, Quaternion.identity);
        ItemCopy.transform.Translate(Vector3.right * Random.Range(-3,3), Space.Self);
    }

    if ( Players == 0 )
    {
        RaceEndDelay -= Time.deltaTime;

        if ( RaceEndDelay <= 0 )
        {
            Application.LoadLevel("end");
        }
    }
}

//This script displays the HUD, with current weapon, ammo left, Health, Shield, and score
var GUIskin:GUISkin; //The skin gui we'll use
var CountdownTextures:Texture2D[];
private var CountdownTextureIndex:int = 0;

function OnGUI()
{
    GUI.skin = GUIskin; //The skin gui we'll use

    if ( CountDownToStart > Time.timeSinceLevelLoad )
    {
        GUI.DrawTexture(Rect( (Screen.width - CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].width) * 0.5, (Screen.height - CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].height) * 0.5, CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].width, CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)].height), CountdownTextures[Mathf.Round(Time.timeSinceLevelLoad)]); //Draw the HUD texture
    }
}

1 个答案:

答案 0 :(得分:2)

Mathf.Round(Time.timeSinceLevelLoad)只是更大的CountdownTextures数组大小。

也许尝试添加:

Debug.Log("Index: "+Mathf.Round(Time.timeSinceLevelLoad)+", Array size: "+ CountdownTextures.Length);

你应该看到索引大于大小。

你也可以在里面添加一些安全检查,如下所示:

if(Mathf.Round(Time.timeSinceLevelLoad) < CountdownTextures.Length && <your second statement>)