找回密码
 立即注册
查看: 271|回复: 0

[笔记] Unity “父子关系”

[复制链接]
发表于 2022-5-17 11:13 | 显示全部楼层 |阅读模式
在 Unity 中, 有的时候用脚本生成的 GameObject,我会想 Group 它们,查了一下代码:
childObject.transform.parent = parentObject.transform;
有点意思,其实我以为会直接指定 parent,没想到居然用到 transform 组件。
Transform 组件

Transform 这个组件是 GameObject 一定有的,即使这个 GameObject 是 Empty GameObject,但它一定有 Transform 组件:
A GameObject will always have a Transform component attached - it is not possible to remove a Transform or to create a GameObject without one.
当存在“父子关系”的时候,就有了世界坐标系和局部坐标系的概念,经典的利用“父子关系”以及局部坐标系的例子比如:旋转的房门。
管理


  • 移动 parent object 会移动所有的 child object
  • 缩放 parent object 会缩放所有的 child object
  • 销毁 parent object 会销毁所有的 child object
这些都是使用 parent 来管理一群同类物体的好处,比如:
Destroy(parent);
相比使用 Tag 来管理的话代码更简短一些:
void DestroyWithTag (string destroyTag)
{
    GameObject[] destroyObject;
    destroyObject = GameObject.FindGameObjectsWithTag(destroyTag);
    foreach (GameObject oneObject in destroyObject){
        Destroy (oneObject);
    }   
}
参考:

  • Transforms
  • Transform.parent
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-3 07:32 , Processed in 0.087734 second(s), 25 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表