如何修复'数组索引超出范围错误'在Unity3D中

时间:2015-08-31 05:33:18

标签: c# unity3d

我一直在关注Udemy上的“通过制作游戏学习代码”(在Unity 4.6.3中)中的Block Breaker部分。我决定在游戏中采取略微不同的路径并挑战自己。但是我有一些问题。所以我的想法是,当一个球击中屏幕底部的对撞机(名为loseCollider)时,玩家将失去1点生命(其中有5点)。从目前为止我在游戏下方的屏幕截图中可以看到,有5个心脏,每个都附有一个精灵。我想要的是让球击中loseCollider并根据lostCollider被击中的次数改变心灵的精灵。但是我不断收到此错误消息:

Error Message

以下是代码:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LoseCollider : MonoBehaviour {

private LevelManager levelManager;

public Sprite[] lives;

public GameObject lives1;
public GameObject lives2;
public GameObject lives3;
public GameObject lives4;
public GameObject lives5;

private int amountHit;
private int maxHit = 5;


void Start () {
    levelManager = GameObject.FindObjectOfType<LevelManager>();
}

void OnTriggerEnter2D (Collider2D trigger) {
    print ("Trigger");
}

void OnCollisionEnter2D (Collision2D collision) {
    LoadSprites ();
    print ("Collider");
    amountHit++;
    print (amountHit);
    if(amountHit == maxHit){
        levelManager.LoadLevel("Lose");
    }
}

void LoadSprites () {
    int spriteIndex = 1;

    lives1.GetComponent<SpriteRenderer>().sprite = lives[spriteIndex];

    if(amountHit >= 1){
        print ("Hit 1");
        lives1.GetComponent<SpriteRenderer>().sprite = lives[spriteIndex];
    } else if(amountHit >= 2){
        print ("Hit 2");
        lives2.GetComponent<SpriteRenderer>().sprite = lives[spriteIndex];
    } else if(amountHit >= 3){
        print ("Hit 3");
        lives3.GetComponent<SpriteRenderer>().sprite = lives[spriteIndex];
    } else if(amountHit >= 4){
        print ("Hit 4");
        lives4.GetComponent<SpriteRenderer>().sprite = lives[spriteIndex];
    } else if(amountHit >= 5){
        print ("Hit 5");
        lives5.GetComponent<SpriteRenderer>().sprite = lives[spriteIndex];
    }
}

游戏截图: Screenshot

1 个答案:

答案 0 :(得分:0)

从你的代码:

int spriteIndex = 1;
lives1.GetComponent<SpriteRenderer>().sprite = lives[spriteIndex];

你在lives数组填充了什么吗?尝试访问索引&gt; =数组大小的数组将导致像您的错误。如果不知道你在编辑器中填充lives数组的内容,很难说,但我首先要将spriteIndex设置为0。