Search code examples
c#arraysunity-game-engineindexingcircular-buffer

Unity array, get current index -x or +x


How I can achieve getting the current index -5 for example. I know how to get the current index and I can subtract or add to that index, but this will cause Array out of bounds errors. Let's say the array has 15 items (index 0/14) and my current index is 2 if I will subtract 5 it will return -3. And this doesn't exist in the array. Now what I want is that when the index is 2 and I substract 5 it returns 11, so it should always loop through the array. The same applies for adding 5 obviously.


Solution

  • You can create an extenstion method like this:

    public static int ComputeCircularIndex(this Array arr, int i) 
    {
       int N = arr.GetLength(0);
       if (i < 0) 
       {
           i = N + (i % N);
       } 
       else 
       {
           i = i % N;
       }
       return i;
    }