[help] Array index is out of range
So in another script i call the method loselife(); when an object is triggered and when the method is called it says ' Array index is out of range' i changed this.getcomponent().sprite=[lives-1] to this.getcomponent().sprite=[1] and it seemed to work, so why does it not work the first time is my question.
Here is the code :
using UnityEngine; using System.Collections;
public class Lives : MonoBehaviour {
public Sprite[] liveSprites;
private int lives;
private int liveIndex;
private LevelManager LevelManager;
void start() {
LevelManager = GameObject.FindObjectOfType<LevelManager>();
lives = 3;
}
public void loseLife() {
lives--;
assignSprite();
}
void assignSprite() {
this.GetComponent<SpriteRenderer>().sprite=liveSprites[lives - 1];
}
}
Does the error occur each time you call assignSprite()? The out of range error means you are accessing an index of the array that doesn't exist. For example, say you had an array with 5 values contained in it. You could access indexes 0,1,2,3 and 4. If you tried to access index -1 or index 5 you would receive that error. It looks like once Lives has been decremented to 0, your code is attempting to access index -1. You should put a conditional check to see if lives it at zero before you try to access lives-1. Then you can delete the gameobject or whatever you need to do.
This probably isn't the best place to do this check, but it is the last possible point to do so. It would probably be better to do this check in loseLife() before you ever call assign sprite unless you want to assign a specific sprite on death.
void assignSprite() {
if(lives == 0){
//Do something when the object is out of lives ie:
$$anonymous$$illActor(this.gameobject);
}
this.GetComponent<SpriteRenderer>().sprite=liveSprites[lives - 1];
}
@tjmarshall I tried to put some print statements in to see what the value of lives was and this was the output into the console "2, -1, 1, -1" only 4 outputs even though i had 6 print statements, i also did something when the user runs out of lives, however it just takes me on to the next level after loosing only one life. here is the code
using UnityEngine; using System.Collections;
public class Lives : $$anonymous$$onoBehaviour {
public Sprite[] liveSprites;
private int lives;
private int liveIndex;
void start (){
lives = 3;
print ("3");
print (lives);
}
public void loseLife() {
lives--;
print("2");
print (lives);
assignSprite();
}
void assignSprite() {
if (lives <= 0) {
Application.LoadLevel(Application.loadedLevel+1);
}
print ("1");
print (lives);
this.GetComponent<SpriteRenderer>().sprite=liveSprites[0];
}
}
Questions about debugging code does not belong to Unity Answers. By the way, start
!= Start
, thus, lives
is never assigned