zoukankan      html  css  js  c++  java
  • 如何 正确 删除 子物体

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

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

     

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

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

  • 相关阅读:
    #敏捷个人# 每日成长101:第72天【自我接纳】
    如何从敏捷个人架构图看出时间管理的演变
    #敏捷个人# 每日成长101:第73天【选择】
    2012年度总结:内心宁静的2012
    欢迎关注敏捷个人微信公众帐号
    敏捷个人的创立与详解Scrum会议
    学习敏捷个人卡片V1.0
    #敏捷个人# 每日认识101(11):做自己的医生
    #敏捷个人# 面向对象分析与PPT有什么关系?
    《敏捷个人-认识自我,管理自我 v0.6.pdf》配套PPT打印书籍
  • 原文地址:https://www.cnblogs.com/chongxin/p/4114489.html
Copyright © 2011-2022 走看看