List - Index out of range error

Hello, I wanted to try doing this using a for loop instead of foreach, but I get Index out of range error. I thought lists had variable range, so they would keep expanding as we add more elements, right?

Hi,

Have you already tried to add Debug.Logs to your code to see what is going on during runtime?

When I used Debug.Log(path.Count) to get its length, it kept showing 0.
It works if I use path.Add() . So the Add function creates new indexes and adds the elements, but
“path[i] = waypoint;” wont create new indexes, it will only assign to the one already present, I guess.

Good job on analysing and solving the problem. You are right. :slight_smile:

If path.Count is 0, there are no “slots” in that List, thus you cannot access the first “slot” via path[0] (and therefore also not path[i] with i >= 0).

To add an element to the List, call path.Add(waypoint). That will create a new “slot” with an index.

1 Like

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

Privacy & Terms