- Home /
Index out of Range Exception Error
Can't seem to find the issue.. I have checked all of my gameobjects and my script is only on one of them. The error I'm getting is:
IndexOutOfRangeException: Array index is out of range. SelectCharacter.Update () (at Assets/Scripts/SelectCharacter.cs:17)
This is the main script
using UnityEngine;
using System.Collections;
public class SelectCharacter : MonoBehaviour {
public static int chickenSelect;
public bool rainbowUnlocked;
public bool halloweenUnlocked;
public SpriteRenderer Chicken;
public Sprite[] chickenSprite;
void Start(){
chickenSelect = 0;
}
void Update(){
Chicken.sprite = chickenSprite [chickenSelect];
if(chickenSelect > chickenSprite.Length){
chickenSelect = 0;
}
if (chickenSelect < chickenSprite.Length) {
chickenSelect = chickenSprite.Length;
}
}
}
Then I have some scripts on my arrow buttons:
using UnityEngine;
using System.Collections;
public class RightArrow : MonoBehaviour {
void OnMouseDown(){
SelectCharacter.chickenSelect++;
}
}
and left one
using UnityEngine;
using System.Collections;
public class LeftArrow : MonoBehaviour {
void OnMouseDown(){
SelectCharacter.chickenSelect--;
}
}
If anyone knows why I am gettting the error it would be very helpful.
Answer by Unitraxx · Oct 25, 2014 at 07:47 PM
I see 1 mistake that's definitely going to cause an index out of range since you assume that chickenSprite.Length
is the last index, while chickenSprite.Length - 1
is the last index.
And then you also want your index adaptation to happen before the actual access which gets you:
void Update(){
if(chickenSelect > chickenSprite.Length){
chickenSelect = 0;
}
if (chickenSelect < chickenSprite.Length) {
chickenSelect = chickenSprite.Length - 1;
}
Chicken.sprite = chickenSprite [chickenSelect];
}
Hmm I kinda assumed that the initialization was just not included in the sample, but you are definitely right. Another strange thing is that it never gets populated with any values (which would've thrown a more suiting Exception if not initializing is also part of the problem.)
Thanks for your help guys! Got things figured out and working.
Answer by Pathojen · Mar 23, 2019 at 12:29 AM
Hello.
I have the same issue in my project, but I haven't even written any scripts. All I did was import a few sprites and animations. (Another issue is that my console will not pop up for me to get a better look at it, which I think is odd.) Any advice on what might be going on? Thanks in advance.
The error did not occur until after I switched the platform to mobile.
Your answer
Follow this Question
Related Questions
Alter a GameObjects(Clone) array from another script C# 0 Answers
Multiple Tiled GPU warning: RenderTexture color surface errors? 0 Answers
Wierd IndexOutOfRangeException : Array index is out of range 1 Answer
What's a more efficient way to sort an array into multiple groups? 1 Answer
Replace float v=Input.GetAxis("Vertical") with touch? 0 Answers