List<GameObject>.Count in loop PROBLEM

I need an advice, code below working just if change loop to


for (var i = 0; i < 10; i++)
{
… // i have 10 waypoints
}

but, if I do as in the screenshot , I will get an error:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

i tried to make

int blabla = _wayPoint.Count + 1

for (var i = 0; i < blabla; i++)

but it did not help… im literally cant fix that 2 days, maybe someone have solution?

i know, my eng is perfect but i hope you will understand what I wrote, ty

Seems like you want to make waypoints for every child? Here’s the solution:

void GetWayPoints()
{
  for (var i = 0; i < WayPointParent.transform.childCount; i++)
  {
    _wayPoints.Add(WayPointParent.transform.GetChild(i).gameObject);
  }
}
Why your previous loop doesn't work

Your other code doesn’t work because you’re looping through _waypoint.Count, which gets increased every time you do _waypoint.Add. So in your previous loop, it will do

_waypoint.Count = 10, i = 0
_waypoint.Add called
_waypoint.Count = 11, i = 1
_waypoint.Add called
_waypoint.Count = 12, i = 2
etc…

Which will run forever until Transform.GetChild(index) throws the ArgumentOutOfRangeException. This is because i will always be less than _waypoint.Count.

THANK YOU SO MUCH, its finally works with ur help and ty for explanation.