So, lets say I’ve got an array(a builtin array, but that doesn’t really matter for the question) and I want to assign some values to the gameobjects in them.
I get these values from another array, but the numbers may be shifted by x amount.
So to assign the right values to the right objects I would need to shift the element I get by using something along the lines of:
array[i+x] = value*;* Obviously doing something like this will leave the first x elements in array empty, and gives an index out of range on the last x elements.
What I need to do to fix this is to check if i+x is higher than the length of array, and if so i should be 0. I think. Is there any elegant way of doing this?
Sounds like what you want is the modulus function: %. This takes the first value, and returns the remainder when divided by the second value, so, for example, 10%6 will give 4. I assume you want to wrap the elements round, so the last x values becomes the first x values, in which case this is the perfect solution - you simply use the same code, but taking the modulus of the length! So, instead of using array[i+x], you’d use array[(i+x)%array.Length]. This ensures that the value can never be equal to or greater than the length of the array, and if the given value (i+x) is, then it will wrap around, meaning that if i+x is equal to the array length, it will index into the array at 0, and if it is one greater than the array length, it will index in at 1, etc.