美文网首页Unity3d游戏开发
Unity3d 如何移除某个GameObject的所有子物体

Unity3d 如何移除某个GameObject的所有子物体

作者: 王广帅 | 来源:发表于2020-02-19 23:15 被阅读0次

在开发游戏的时候,经验会遇到这样的需求:移除某个物体下面的所有子物体,比如排行榜列表的刷新,清空某个列表等。虽然Unity3d提供了一些现成的API可以操作,但是要正确移除一个物体下的所有子物体,还需要注意一些问题

  1. 通过Transfrom的childCount属性可以获取当前物体有多少个子物体
parent.transform.childCount
  1. 通过transform.get(index)方法返回的是子物体的transform,直接移除是不对的
            Transform transform;
            for(int i = 0;i < parent.transform.childCount; i++)
            {
                transform = parent.transform.GetChild(i);
                GameObject.Destroy(transform);//这里移除的是transform组件,运行的时候会报错
            }
  1. 在移除的过程中,不会立刻改变childCount的数量,下面这种写法是错误的,会造成死循环
            while(parent.transform.childCount > 0)
            {
                Transform transform = parent.transform.GetChild(0);
                GameObject.Destroy(transform.gameObject);
            }
  1. 还有一个错误是调用DetachChildren,该方法不会删除子游戏物体,只是解除了父子关系,所有的子物体将直接成为场景内的物体存在。
parent.transform.DetachChildren();
  1. 正确移除是这样的
 public static void RemoveAllChildren(GameObject parent)
        {
            Transform transform;
            for(int i = 0;i < parent.transform.childCount; i++)
            {
                transform = parent.transform.GetChild(i);
                GameObject.Destroy(transform.gameObject);
            }
        }
求关注,求打赏.png

相关文章

网友评论

    本文标题:Unity3d 如何移除某个GameObject的所有子物体

    本文链接:https://www.haomeiwen.com/subject/wbazfhtx.html