user8747104
user8747104

Reputation:

Pre-decrement of value in a for loop is not correctly decreasing value on first loop

I have the following for loop in my code (using C#)

for (int i = 150; i >= 75; --i)
{
    print("I holds " + i);
    images[i].gameObject.SetActive(false);
}

trying to run through each item in a list, and disable the object. The list holds 150 objects (but since it starts at value zero, the final reference position is 149)

So, I figured a for loop was a good way to iterate through them all. Yet, I try to decrease the value of i to 149 for the first run of the loop, but it still passes a value of 150 into the loop in the first run, which throws the expected ("Argument is out of range") error.

Can anyone work out why the decreased value isn't correctly being passed to the loop?

I tried both decreasing it before and after the first run of the loop, but both times it passes a value of 150 into the loop.

I feel this should be a relatively simple issue to solve, yet it's not working as I expected it to do!

Upvotes: 1

Views: 687

Answers (2)

4baad4
4baad4

Reputation: 27

for (int i = 10; i >= 0; --i)

is the same as

for (int i = 10; i >= 0; i--)

i does not decrease/increase on the first loop. This is for many languages. Just start with 149 and it works.

Answer for "Can anyone work out why the decreased value isn't correctly being passed to the loop?"

Upvotes: 3

Christos
Christos

Reputation: 53958

Another way to loop through all items of an array without caring of actual indices is to make use of a foreach statement:

foreach(var image in images)
{
    image.gameObject.SetActive(false);
}

If you want to use a for statement. I would suggest you write it as below:

for(var i=0; i<images.Length; i++)
{ 
    image[i].gameObject.SetActive(false);
}

Doing so, you are pretty confident that you are not going to be out of the array's size. You start at the element at the position with index of 0 and you read the last item stored in the array, in the position of images.Length-1.

Update If you want to update only the first 75 items (where 75 is half the total items in the array) in your array you could try this:

for(var i=0; i<images.Length/2; i++)
{ 
    image[i].gameObject.SetActive(false);
}

Upvotes: 2

Related Questions