如何 正确 删除 子物体

 

这几天做项目的时候发现 自己删除子物体之后,再新建子物体,发现原来的子物体的函数依旧被调用了。

后来看了一下,发现是由于子物体绑定了一个父物体的委托,在销毁的时候没有去除父物体的委托。

 

但是这个调试 引发了我另外一个思考:

我发现在删除子物体之后,调用 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/

转载于:https://www.cnblogs.com/chongxin/p/4114489.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值