LoginSignup
15
11

More than 5 years have passed since last update.

UnityのDestroyは即時反映されないので、DestroyImmediateを使う

Last updated at Posted at 2016-03-24

GameObject を Destroy() して、ヒエラルキー上からは消えても、実はしっかり存在している。
GetComponents で要素検索するとふつうにカウントされて返ってくるので、知らないとはまる(はまった)。

ちなみに、対象に null を入れても、GetComponents で取得できてしまう。

Debug.Log (GetComponents<Transform>().Length); // 1
Destroy (targetObject);
targetObject = null;
Debug.Log (GetComponents<Transform>().Length); // 1

(GCに時間かかってる・・?)

で、そういうときは、 DestroyImmediate を使うと即時破棄される。
めでたしめでたしかと思ったが、DestroyImmediate は推奨されてないっぽい。

直ちにオブジェクトを破壊する。ですが、Destroy 関数の方を使うことを推奨します

うーん、 コルーチンで非同期処理にすればよい・・のか?
子要素の全削除なら、Detach してやるって方法もある。

foreach (Transform n in transform)
{
    Destroy(n.gameObject);
}
transform.DetachChildren ();
15
11
0

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
15
11