1

I am currently making an RTS style game. I made this fog of war script for making enimies invisible:

void Update () {
    foreach (GameObject enemy in enemies) {
        if (enemy == null) {
            enemies.Remove (enemy);
            continue;
        } else {
            Visible = false;
            foreach (GameObject vision in visions) {
                if (vision == null) {
                    visions.Remove (vision);
                    continue;
                } else {
                    Vector3 point = enemy.GetComponent<Collider> ().ClosestPoint (vision.transform.position);
                    float range = vision.GetComponent<FieldOfView> ().viewRadius;
                    float distance = Vector3.Distance (point, vision.transform.position);
                    if (distance <= range) {
                        Visible = true;
                        break;
                    }
                }
            }
            MeshRenderer render = enemy.GetComponent<MeshRenderer> ();
            if (Visible) {
                if (!render.enabled) {
                    render.enabled = true;
                }
            } else if (!Visible) {
                if (render.enabled) {
                    render.enabled = false;
                }
            }
        }
    }
}
}

Whenever an enemy gamobject gets destroyed, I get the error in the title. I'm still pretty new at programming and dont see what could be causing the problem. I looked around myself for a bit on other threads with the same problem, but I dont really get how to fix it. Any help is appreciated. If any more information is needed, just ask and I will try and provide it.

Jacob Petersen
  • 63
  • 1
  • 2
  • 6
  • You simply can´t *modify* a list while you´re *iterating* it. That´s what the error states. You can copy your list to a temporary one, iterate that and modify the original. – MakePeaceGreatAgain Sep 15 '17 at 21:09

1 Answers1

6

Look at this bit of your code:

foreach (GameObject vision in visions) {
    if (vision == null) {
        visions.Remove (vision);

Now, look back at the error you're getting:

Collection was modified enumeration operation may not execute.

What it is telling you is that you cannot modify a collection while iterating over it with foreach. That includes adding and deleting elements, as well as modifying existing ones.

There are lots of ways to deal with this issue. In general, the ideal solution would be to refactor your code so that modifying it during iteration isn't necessary. If you don't want to do that however, this dirty fix will also work most of the time:

foreach (GameObject vision in visions.ToList())

In your specific case (removing nulls) however, I would do the following:

visions = visions.Where(i => i != null).ToList();

This will remove all null elements. And then you iterate over it afterwards.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53