Quincy Norbert
Quincy Norbert

Reputation: 451

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.

Upvotes: 0

Views: 1102

Answers (3)

Michał Turczyn
Michał Turczyn

Reputation: 37470

You could use below code to assure that index is in range. It will add length of an array, so negative numbers would be in range. In case of positive, correct indexes, such addition will cause index to go out of range, thus I use mod % operator, to again make sure we are in bounds.

var numbers = Enumerable.Range(0, 15).ToArray();
var idx = 2;
var offset = 5;
idx = (idx - offset + numbers.Length) % numbers.Length;
var el = numbers[idx];

el would be equal to 12.

To assure that big values of offset will be correctly handled, you can use any multiple of numbers.Length, eg.

idx = (idx - offset + 100 * numbers.Length) % numbers.Length;

Upvotes: 1

Nick
Nick

Reputation: 5042

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;
}

Upvotes: 2

user13278024
user13278024

Reputation:

With the modulo operator you can achieve the secondo behavior (increment the index and cycle throw an array) pretty easily. For the first behavior, you need some additional logic. Here's the fiddle.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyClass: MonoBehaviour
{
   private int currentIndex = 0;

   void Increment(int value)
   {
      currentIndex += value;
      currentIndex = currentIndex % 15;
   }

   void Decrement(int value)
   {
      currentIndex -= value;

      if (currentIndex < 0)
          currentIndex = 15 + (currentIndex % 15);
   }
}

Upvotes: 1

Related Questions