Modular arithmetic in Unity

Hi lovely Unity community,

I am trying to do a left and right arrow buttons to scroll through items in an array.

myArray = new Array(one,two,three);

In the right arrow, i specific this statement:

index = (index + 1)%myArray.length;

which it scrolls through from 0 to 2. That is fine.

However, for my left arrow, I specific this:

index = (index - 1)%myArray.length;

which it returns an error "argument out of range" as index returns -1.

This puzzle me because isn't (-1) mod 3 = 2

Appreciate your help. Thanks.

Jser

if (--index < 0) index = myArray.length-1;

That's actually a little faster than using %, though granted not as "neat".

This puzzle me because isn't (-1) mod 3 = 2

Nope, it's -1.