Why use "waypointIndex <= waypoints.Count - 1"?

Why not just use?

if (waypointIndex < waypoints.Count)
{

    }
1 Like

Hi Joao,

That’s a good question. I assume that Rick wanted to emphasise what we are doing here. As for me, I would prefer your solution. In the end, it’s a matter of personal preference, though. Use what you prefer. :slight_smile:


See also:

Does it work though? I was running into an OutOfRangeException:Index was out of range Error, when my enemy reached the last waypoint. I was looking for a solution in the community when I saw this post I realized I didn’t add the -1 to the statement. Using the -1 ensures the List does not look for an Item that is not included, I think.

Hi @SimoninSD82,

ArgumentOutOfRange / IndexOutOfRange exception means that the code tried to access a non-existent index in an array, List or another collection. The first index in an array and List is 0, hence the last index is the number of elements minus 1. For example, if the array has got a length of 2, and the code tries to access index 2, you will get this error message because there are only two “slots” in the array: at index 0 and at index 1.

1 Like

Thank you for the explanation!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms