如何 正確 刪除 子物體


 

這幾天做項目的時候發現 自己刪除子物體之后,再新建子物體,發現原來的子物體的函數依舊被調用了。

后來看了一下,發現是由於子物體綁定了一個父物體的委托,在銷毀的時候沒有去除父物體的委托。

 

但是這個調試 引發了我另外一個思考:

我發現在刪除子物體之后,調用 tranform.childcout 屬性,發現沒有變為0。

刪除子物體代碼如下:

1     void DetoryChilds(Transform tar)
2     {
3         for (int i = tar.childCount - 1; i >= 0; --i)
4         {
5             var child = transform.GetChild(i).gameObject;
6             Destroy(child);
7         }
8     }

 

google 了 一下,原因是因為 object destruction 是在所有的 update 執行之后的。雖然在 DestroyChilds 函數中 銷毀了,但是要在 update 之后才算 真正銷毀,這也是為什么 銷毀了的子物體 還能 響應 父物體的委托(好吧,貌似這是托管的)。

 

 

 

解決:

發現了原因,解決就簡單了。直接上成功代碼吧

 1 IEnumerator Start () {
 2 
 3     yield return new WaitForSeconds(0.5f);
 4 
 5     //foreach (Transform child in transform)
 6     //{
 7     //    Destroy(child);
 8     //}
 9     //Can't destroy Transform component of '1'. If you want to destroy the game object, please call 'Destroy' on the game object instead. Destroying the transform component is not allowed.
10 
11 
12     //-GameObject
13     //    -1
14     //    -2
15     //    -3
16     //    -4
17         
18     //condition is based on the assumption that GetChildCount() is decreased as soon as Destroy() is called.
19 
20     //According to the reference manual, actual object destruction is always delayed 
21     //until after the current Update loop.
22 
23     //your for condition will never be false, and you are caught in an endless loop.
24         
25     //---- wrong
26     //while (transform.childCount > 0)
27     //{
28     //    Destroy(transform.GetChild(0).gameObject);
29     //}
30 
31     //Method 1
32     while (transform.childCount > 0)
33     {
34         Debug.Log(transform.childCount);
35 
36         Destroy(transform.GetChild(0).gameObject);
37             
38         yield return new WaitForEndOfFrame();
39     }
40 
41     //Method 2
42     DetoryChilds(transform);
43     ///沒有變為0
44     Debug.Log(transform.childCount);
45 
46     //can not while (transform.childCount > 0) { } ,it pause at main thread 
47     //you need yield return new WaitForEndOfFrame();
48     yield return new WaitForEndOfFrame();
49     Debug.Log(transform.childCount);
50         
51     if (signal != null) signal();
52 }

 果然 unity3d 還是 有很多坑,需要 細心 查看一下。

 參考:http://forum.unity3d.com/threads/deleting-all-chidlren-of-an-object.92827/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM