Just an FYI for folks if you want to use modular arithmetic for traversing loops. The % operator is not the same as the mod operator. a%b just gives the remainder of a/b. For positive a this is the same as the mod operator. However if a is negative then a%b is not the same as the mod operator.
Here is a general mod function that can handle both positive and negative values (I got it from a number theory text)
private int mod(int a, int b) {
return (int)(a - b * Mathf.Floor((float)a/(float)b));
}
I found I needed this because I wanted to give my NPCs the option of traversing a loop “clockwise” (in order of increasing child index) or “counter clockwise” (in order of decreasing child index). So I have the two following methods for getting the next or previous index
public int GetNextIndex(int idx) {
return mod(idx + 1, transform.childCount);
}
public int GetPreviousIndex(int idx) {
return mod(idx - 1, transform.childCount);
}