Open2

Unityで子のオブジェクトをすべて削除する

kamocyckamocyc
public static class Util3
{
  public static void DestroyAllChildren(this Transform transform)
  {
    // 逆方向にforループを回さないと1つずつ抜ける
    for (int i = transform.childCount - 1; i >= 0; i--)
    {
      U.Destroy(transform.GetChild(i).gameObject);
    }
  }
}

public static class U
{
  public static void Destroy(UnityEngine.Object go)
  {
    if (Application.isPlaying)
    {
      GameObject.Destroy(go);
    }
    else
    {
      GameObject.DestroyImmediate(go);
    }
  }
}

使う

      foo.transform.DestroyAllChildren();
kamocyckamocyc

Destroyは1フレーム後に破棄。DestroyImmediateは即座に破棄。後者はパフォーマンスが悪いがエディタコードではこっちが必要。

https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html

you should never iterate through arrays and destroy the elements you are iterating over

ということで逆からループを回す。

なんか削除しても残っているの謎だと思ったらこれが原因だった。