0
votes

I've been following the Block Breaker section of the course Learn To Code By Making Games (In Unity 4.6.3) on Udemy. I decided to take a slightly different path on the game and challenge myself. However I have some issues. So the idea is that when a ball hits a collider (named loseCollider) at the bottom of the screen, the player will lose 1 life (of which there are 5). As you can see from the screen shot below of my game so far, there are 5 hearts, each with a sprite attached. What I want is to have the ball hit the loseCollider and change the sprite of the hearts according to how many times the loseCollider was hit. However I keep getting this error message:

Error Message

Here is the code:

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];
    }
}

And the screenshot of the game: Screenshot

1
Without any code (please put the code here and not elsewhere), the only answer is - don't try to access an index that is >= to the size of the arrray. - ChiefTwoPencils

1 Answers

0
votes

From your code:

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

Have you filled the lives array with something? Trying to access an array with an index >= the size of the array will cause an error like yours. It's hard to say without knowing what you've filled the lives array with from the editor, but I'd start with setting spriteIndex to 0.