Trouble us if statement inside for loop

Hey, all. I’ve run into something puzzling I can use some advice on. I have a very simple for loop in the Update method which runs based on the number of items I have in a list. In the example below, pos.Count = 3.

void Update()
    {
        for (int i = 1; i < pos.Count; i++)
        {
            print(i);
        }
    }

This code works fine, and prints 1 and 2 repeatedly, as you’d expect. The trouble comes in when I try to nest an If statement inside the for loop. Example below…

        for (int i = 1; i < pos.Count; i++)
        {
            print(i);
            if (Physics.Linecast(pos[i].position, pos[i++].position, mask))
            {
                print("collision");
            }
        }

This just keeps outputting 1. I’m sure it’s something obvious, but I can’t figure out for the life of me why the for loop is not iterating up. No errors thrown. Advice appreciated.

Line 4 contains an embedded i++ increment.

ALSO: beware that if pos is a collection of 3 items, their indices will be 0, 1, 2, so your for loop is starting out by missing the 0th element.

The correct for() loop is:

for (i = 0; i < pos.Count; i++)
{
}
2 Likes

Haha, of course! I’m starting to think you’re the only other person on this forum, Kurt. I hope Unity compensates you for keeping their forum alive. Amended code below…

        for (int i = 0; i < pos.Count - 1; i++)
        {
            print(i);
            if (Physics.Linecast(pos[i].position, pos[i+1].position, mask))
            {
                print("collision");
            }
        }