IndexOutOfRange- Script does not work

Hi, I am working on a 2D platformer. I just created this script so when I touch a button the sprite(of my button) changes.
However when I tested it it gave me an IndexOutOfRange error. Could someone tell me how to fix this? THANK YOU!

Knipsel

You need to check if hitSprites exists and what length it is. You’re trying to call hitSprites[0] in this case but if the hitSprites array is empty the the index will be out of range.

Something like.

if(spriteIndex < hitSprites.Length){
     this.GetComponent<SpriteRenderer>  .......
}
1 Like

Hi Elias,

Looking at that screenshot, your SpriteIndex value is always going to equal zero as you set the index to equal a value of 1 and then, based on the logic, instantly deduct the value of 1 away from it. With that condition being met, the code within the else if will not be reached.

So, line 22 then requests hitSprites[0] and you receive an IndexOutOfRange error, I can only assume in this instance that the hitSprites array doesn’t contain any elements, e.g. you’ve not initialised it.

Note, you can also just copy and paste your code into the forum posts and very easily format it (makes it much easier for us to help).


See also;

Hi thank you for the reply, I fixed this issue. I still have one issue now, when I walk over it it changes for a very short time and than turns to back to the original sprite… for some reason it collides 2 times as my debug.log gets called 2 times when I go over it.

	public Sprite[] hitSprites;


	int SpriteIndex = 1;
	void OnTriggerEnter2D ()
	{
		Debug.Log("b collided");
		if (SpriteIndex == 1) {
			SpriteIndex = 0;
			Debug.Log(SpriteIndex);
		} else if (SpriteIndex == 0) {
			SpriteIndex = 1;
			Debug.Log(SpriteIndex);
		}
		this.GetComponent<SpriteRenderer> ().sprite = hitSprites[SpriteIndex] ;


	}
}
1 Like

Might need to know a little bit more about the context here.

  • “when I walk over it” - as in something in the scene walks over it, or, are you tapping/pressing a button?
  • “my debug.log gets called 2 times” - which one? You have three in that code snippet
  • is your script attached to more than one GameObject?
  • is your script attached to a disabled GameObject?
  • if you need to consider whether the colliding game object is still triggering, have you considered using OnTriggerStay2D?

See also;

Privacy & Terms