0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

UnityのC#で実装時に「InvalidOperationException: Collection was modified」エラーが出た時は

Posted at

背景

配列の操作を実装していたらこんなエラーが出た

InvalidOperationException: Collection was modified; enumeration operation may not execute.

おや?

やっていることは

foreach (型 data in dataList)
{
    〜
    if (条件)
    {
         dataList.Remove(data);
    }
}

のような処理である。

ググってみると「ループ内で要素・行を追加また削除すると発生します」とのことらしい。

解決法

以下のように対応

List<型> tmpDataList = new List<型>(dataList);

foreach (型 data in tmpDataList)
{
    〜
    if (条件)
    {
         dataList.Remove(data);
    }
}

これで解決!

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?