Home > Software design >  How to skip over deleted items in a Transform inside a loop?
How to skip over deleted items in a Transform inside a loop?

Time:01-03

I have code which loops through a Transform and sends each GameObject in said transform to a waypoint. This bit works fine.

This issue however comes when I delete a GameObject inside the transform using Collision. The objects indexed in the Transform after the one that gets deleted get thrown off the waypoint path. (The ones indexed before the deleted one stay on).

My question is how can I get my ForLoop to skip over the deleted elements in the Transform so that the program doesn't "break" as such.

I gather that there is probably a rather simple solution to this but I did look online and there is very few articles on this.

private void MoveToNextWaypoint()
{
    for (int i = 0; i < targets.Count; i  )
    {
        var targetWaypointTransform = _waypoints[_nextWaypointIndex];
        targets[i].MoveTo(targetWaypointTransform.position, MoveToNextWaypoint);
        targets[i].transform.LookAt(_waypoints[_nextWaypointIndex].position);
        _nextWaypointIndex  ;

        if (_nextWaypointIndex >= _waypoints.Count)
            _nextWaypointIndex = 0;
    }
}

(Breaks on the first targets[i] line)

Thank you for any help!

Note: The objects will not necessarily be deleted in order.

CodePudding user response:

Your question seems to boil down to this line:

how can I get my ForLoop to skip over the deleted elements in the Transform

The answer would be:

private void MoveToNextWaypoint()
{
    for (int i = 0; i < targets.Count; i  )
    {
        if (targets[i] == null) continue;
        var targetWaypointTransform = _waypoints[_nextWaypointIndex];
        targets[i].MoveTo(targetWaypointTransform.position, MoveToNextWaypoint);
        targets[i].transform.LookAt(_waypoints[_nextWaypointIndex].position);
        _nextWaypointIndex  ;

        if (_nextWaypointIndex >= _waypoints.Count)
            _nextWaypointIndex = 0;
    }
}

Note the first conditional in the for loop, checking whether an element in the array is null. The overloaded equality == not only checks if an item is null, but also if the underlying managed object is set for removal as well.

We can’t see a big portion of your code, but you suggest you’re getting your array from the Transform, which if done this frame, might, for a small window of time, still contain items that have been marked for destruction. But the last comment is conjecture.

  • Related