Quick answer: foreach throws this when the List, Dictionary or HashSet it is walking gets an Add, Remove, Clear or element assignment before the loop ends. In a game the change is usually indirect: a callback, an OnDisable or a spawn that touches the list being looped. Remove items with a reverse for loop or RemoveAll, or queue additions and removals and apply them after the loop.

Double-click this error and Unity opens a foreach line that changes nothing. That is the first thing to understand about it: the exception is raised by the loop, one step after some other code altered the collection, and the stack trace never mentions that other code. This guide explains the check that produces the error, the ways a game ends up modifying a list in the middle of its own update, how to catch the line that did it, and the fixes with their trade-offs, including a Dictionary behaviour that differs between Unity and current .NET.

The exact error

InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.List`1+Enumerator[T].MoveNextRare () (at <hash>:0)
System.Collections.Generic.List`1+Enumerator[T].MoveNext () (at <hash>:0)
EnemyManager.Update () (at Assets/Scripts/EnemyManager.cs:21)

Depending on the Unity version, a System.ThrowHelper line may sit above the enumerator frames. For a dictionary the frame is System.Collections.Generic.Dictionary`2+Enumerator[TKey,TValue].MoveNext (). Line 21 in this example is the foreach statement, and the code looks like this:

foreach (Enemy enemy in enemies)        // line 21: reported here
{
    if (enemy.IsDead)
        enemies.Remove(enemy);          // the actual cause, not in the trace
}

It fires in the editor and in every kind of player build, with the same message.

Why foreach throws

A List<T> keeps a private version number. Add, Insert, Remove, RemoveAt, RemoveAll, Clear, Sort, Reverse and assigning an element through the indexer all increase it. When foreach starts, the enumerator copies the version, and every call to MoveNext compares its copy with the list. A mismatch means the list changed underneath the loop, and the enumerator throws instead of guessing which elements it should still visit. Dictionary, HashSet, Queue, Stack and LinkedList work the same way.

Three details follow from that mechanism:

How games end up doing this

  1. Removing dead things inside the loop. The code above: enemies, bullets, expired buffs or finished timers removed from the list while it is being walked.
  2. The loop body calls something that unregisters. enemy.Tick() kills the enemy, the death code calls manager.Unregister(this), and the manager is in the middle of its foreach. Pooling is the classic route: gameObject.SetActive(false) runs OnDisable immediately, and OnDisable removes the object from the manager’s list. Destroy is deferred to the end of the frame, so OnDestroy does not run inside your loop, but SetActive(false), enabled = false and DestroyImmediate run their callbacks on the spot.
  3. Spawning during the update. A unit’s update splits it in two or fires a projectile, and the new object’s OnEnable adds it to the list being iterated.
  4. A hand-rolled listener list. You loop over a List<IListener> to notify listeners, and one of them removes itself, or subscribes another, in its callback. A C# event does not have this problem, because delegates are immutable and the invocation in progress is unaffected. A list of listeners does.
  5. Writing to a dictionary while enumerating it. Updating cooldowns with cooldowns[key] -= Time.deltaTime inside foreach (var key in cooldowns.Keys), or removing expired entries in the loop. In Unity both throw. See the dictionary section.
  6. Another thread. A network or loading thread adds to a list that the main thread iterates. This version is intermittent, and it is the less dangerous symptom: an unsynchronized List<T> can also corrupt itself without any exception.

If the stack trace contains none of your own code, only editor or package frames (UI Toolkit, Addressables windows and similar), the bug is in that package. Update it and move on.

How to find the code that modified the collection

The trace gives you the loop. To find the writer:

  1. Read the loop body and follow every call it makes. Anything that can kill, disable, spawn or notify can come back to the collection.
  2. Make the collection private and route every change through two methods, Register and Unregister. Now there are only two places a write can happen.
  3. Put a tripwire in those methods. It reports at the moment of the modification, with the stack trace the exception lacks:
bool iterating;

public void Unregister(Enemy enemy)
{
    if (iterating)
        Debug.LogError("Unregister called while EnemyManager is iterating");
    enemies.Remove(enemy);
}

void Update()
{
    iterating = true;
    try
    {
        foreach (Enemy enemy in enemies)
            enemy.Tick();
    }
    finally
    {
        iterating = false;
    }
}

The Debug.LogError entry in the Console shows the full call chain, for example Enemy.OnDisable, Enemy.Die, Enemy.Tick, EnemyManager.Update. If the tripwire never fires and the exception still appears now and then, log System.Threading.Thread.CurrentThread.ManagedThreadId in the write methods and compare it with the value on the main thread.

Fix 1: remove with a reverse for loop

for (int i = enemies.Count - 1; i >= 0; i--)
{
    if (enemies[i].IsDead)
        enemies.RemoveAt(i);
}

Going backwards matters. Removing index i shifts only the elements after it, which you have already visited. A forward loop that removes skips the element that slides into the freed slot unless you also decrement i. When order does not matter, avoid the shift entirely by overwriting the dead entry with the last one:

enemies[i] = enemies[enemies.Count - 1];
enemies.RemoveAt(enemies.Count - 1);

A plain indexed for loop also tolerates additions: items appended during the pass are visited in the same pass, because Count is read every time. Decide whether you want that. It does not protect you if the body removes an element at a lower index.

Fix 2: RemoveAll for filter-style removal

enemies.RemoveAll(e => e.IsDead);

RemoveAll walks the list once and compacts it, where calling Remove repeatedly searches the list for every item. The predicate can do the cleanup too, as long as it does not touch the list:

enemies.RemoveAll(e =>
{
    if (!e.IsDead) return false;
    pool.Release(e);
    return true;
});

A lambda that captures a variable allocates each time it is created. For a loop that runs every frame, the reverse for loop is the allocation-free choice.

Fix 3: iterate over a copy

foreach (Enemy enemy in enemies.ToArray())
    enemy.Tick();          // free to register and unregister

This is the smallest change and it is correct, at a price: ToArray and ToList allocate a new collection on every call. In a once-per-level event that is irrelevant. In Update it is garbage every frame, which ends in garbage collection stutter. Reuse a buffer:

readonly List<Enemy> buffer = new List<Enemy>();

void Update()
{
    buffer.Clear();
    buffer.AddRange(enemies);
    foreach (Enemy enemy in buffer)
    {
        if (enemy != null && enemy.isActiveAndEnabled)
            enemy.Tick();
    }
    buffer.Clear();
}

A snapshot still contains items that were removed or destroyed earlier in the same pass, hence the check before Tick. Skip it and you swap this error for a MissingReferenceException. If the method can be re-entered, one shared buffer is not enough; take a temporary list from UnityEngine.Pool.ListPool<T> (Unity 2021.1 and later) with using (ListPool<Enemy>.Get(out var snapshot)).

Fix 4: defer adds and removes until the loop is done

For a manager that many objects register with, make the manager itself safe so callers do not need to know whether it is iterating:

readonly List<Enemy> enemies = new List<Enemy>();
readonly List<Enemy> pendingAdd = new List<Enemy>();
readonly List<Enemy> pendingRemove = new List<Enemy>();
bool iterating;

public void Register(Enemy e)
{
    if (iterating) pendingAdd.Add(e); else enemies.Add(e);
}

public void Unregister(Enemy e)
{
    if (iterating) pendingRemove.Add(e); else enemies.Remove(e);
}

void Update()
{
    iterating = true;
    try
    {
        foreach (Enemy e in enemies)
            e.Tick();
    }
    finally
    {
        iterating = false;
    }

    foreach (Enemy e in pendingRemove) enemies.Remove(e);
    foreach (Enemy e in pendingAdd) enemies.Add(e);
    pendingRemove.Clear();
    pendingAdd.Clear();
}

New objects start ticking on the next frame, and an object that unregistered before the loop reached it is still ticked once, so keep an alive check inside Tick if that matters. The try/finally keeps one exception in a Tick from leaving the flag stuck on.

Dictionaries: what Unity allows and what current .NET allows

Microsoft’s documentation states that from .NET Core 3.0 on, Remove and Clear do not invalidate a Dictionary enumerator, so removing entries inside a foreach works there. Unity 2022 LTS and Unity 6 do not ship that implementation. In the class library used by Unity’s Mono runtime, which IL2CPP builds are converted from, Add, Remove, Clear and the indexer setter all increase the version, even when the setter only overwrites an existing key. Code copied from a recent .NET answer can therefore throw in Unity.

// Throws in Unity
foreach (var pair in cooldowns)
{
    if (pair.Value <= 0f)
        cooldowns.Remove(pair.Key);
}
// Works on every runtime
keys.Clear();
keys.AddRange(cooldowns.Keys);          // keys is a reusable List<string>
foreach (string key in keys)
{
    float remaining = cooldowns[key] - Time.deltaTime;
    if (remaining <= 0f) cooldowns.Remove(key);
    else cooldowns[key] = remaining;
}

Copying the keys first covers both the update and the removal. Because this is a property of the runtime library and not of the C# language, test it again after a major engine upgrade instead of assuming either behaviour.

When another thread is the writer

None of the fixes above help if a background thread writes to the collection. Give the thread its own thread-safe queue and let the main thread move the items across:

readonly ConcurrentQueue<NetMessage> inbox = new ConcurrentQueue<NetMessage>();

void OnMessageReceived(NetMessage message)   // network thread
{
    inbox.Enqueue(message);
}

void Update()                                // main thread
{
    while (inbox.TryDequeue(out NetMessage message))
        Handle(message);
}

The same structure solves can only be called from the main thread errors, which tend to appear in the same code. Job system containers such as NativeArray are a separate topic: their safety system raises its own InvalidOperationException about jobs reading and writing the same data.

How to confirm the fix

Reproduce the worst case on purpose. Kill several enemies in the same frame, including the first and the last in the list. Spawn from inside an update. Return objects to a pool during the loop. Have a listener unsubscribe in its own callback. If you kept the tripwire from the diagnosis step, it should stay silent through all of it, or fire only on paths you have now made safe. Then profile a busy frame and confirm the fix did not add a per-frame allocation.

Catching the intermittent ones in released builds

This error is often timing dependent: it needs two enemies to die in one frame, or a spawn to land during an update, so it can pass every test and still reach players. The Bugnet Unity SDK files it automatically with the stack trace, recent log lines, platform and game version, and identical titles stack into one entry with an occurrence count, which tells you how often it really happens. The limit is the one described above: the trace names the loop, not the writer, and Bugnet cannot recover what the runtime never recorded. Leave the Debug.LogError tripwire in the build and it closes the gap, because the SDK files error logs too, and that entry carries the call chain of the code that modified the list. Reports land in the dashboard described in the bug reports guide.

Frequently asked questions

What does Collection was modified; enumeration operation may not execute mean?

A foreach loop was walking a List, Dictionary or similar collection, and the collection was changed before the loop finished. The enumerator notices on its next step and throws, because it can no longer know which elements it should visit.

How do I remove items from a list while looping over it in Unity?

Loop backwards with an indexed for loop and call RemoveAt, or call RemoveAll with a condition. Both avoid the enumerator entirely. If other code needs to add or remove during the loop, queue those changes and apply them after the loop ends.

Can I remove entries from a Dictionary inside foreach in Unity?

No. Current .NET allows Remove and Clear during enumeration, but the class library in Unity 2022 LTS and Unity 6 invalidates the enumerator on any change, including overwriting a value. Copy the keys to a list first, then loop over that list and modify the dictionary.

Why does the error point at the foreach line and not at the line that changed the list?

The check runs when the loop asks for the next element, which happens after the code that changed the collection has already returned. Only the loop is on the call stack at that moment, so only the loop appears in the stack trace.

Is looping over ToArray or ToList a good fix?

It is correct and quick to apply, but each call allocates a new collection. That is fine for occasional events and wasteful in Update, where it creates garbage every frame. For per-frame loops, copy into a reusable buffer or use a reverse for loop.

The stack trace shows the loop that noticed the change, never the code that made it. Put a flag around the loop and log from Add and Remove to get the trace you need.