GameObject 与组件系统

3.1 GameObject 的概念

GameObject(游戏对象)是 Unity 中一切物体的基类。任何存在于场景中的东西都是 GameObject。

空对象

右键 → Create Empty 创建一个空 GameObject,它只有一个 Transform 组件:

  • Position:位置 (x, y, z)
  • Rotation:旋转 (x, y, z)
  • Scale:缩放 (x, y, z)

空对象本身不可见,常作为容器逻辑控制点使用。


3.2 组件(Component)系统

组件是 GameObject 的功能模块。GameObject 是一个容器,组件赋予它具体的能力。

组合模式

1
2
3
4
5
6
7
GameObject "Player"
├── Transform → 位置/旋转/缩放
├── MeshRenderer → 渲染模型
├── MeshFilter → 模型网格数据
├── BoxCollider → 碰撞体
├── Rigidbody → 物理模拟
└── PlayerController → 自定义脚本

常用内置组件

组件 功能
Transform 必选组件,定义空间变换
MeshRenderer 渲染 3D 模型
SpriteRenderer 渲染 2D 精灵
Collider 碰撞检测(Box/Sphere/Capsule/Mesh等)
Rigidbody 物理模拟(重力、力的作用)
Light 光源
Camera 摄像机
AudioSource 音频播放
ParticleSystem 粒子特效

3.3 操作组件的 API

获取组件

1
2
3
4
5
6
7
8
9
10
11
// 获取自身组件
Rigidbody rb = GetComponent<Rigidbody>();

// 获取子对象的组件
Rigidbody rbInChild = GetComponentInChildren<Rigidbody>();

// 获取父对象的组件
Rigidbody rbInParent = GetComponentInParent<Rigidbody>();

// 获取多个组件
Rigidbody[] allRigidbodies = GetComponents<Rigidbody>();

添加和移除组件

1
2
3
4
5
6
7
8
9
// 添加组件
Rigidbody rb = gameObject.AddComponent<Rigidbody>();

// 移除组件(不能直接移除 Transform)
Destroy(GetComponent<BoxCollider>());

// 启用/禁用组件
Collider collider = GetComponent<Collider>();
collider.enabled = false; // 关闭碰撞检测

3.4 Transform 组件详解

位置

1
2
3
4
5
6
7
8
9
// 世界坐标
Vector3 worldPos = transform.position;

// 本地坐标(相对父级)
Vector3 localPos = transform.localPosition;

// 移动
transform.Translate(1, 0, 0); // 相对自身方向移动
transform.Translate(1, 0, 0, Space.World); // 相对世界坐标移动

旋转

1
2
3
4
5
6
7
8
// 欧拉角
Vector3 euler = transform.eulerAngles;

// 旋转
transform.Rotate(0, 90, 0); // 绕 Y 轴旋转 90 度

// 看向目标
transform.LookAt(targetObject);

缩放

1
2
3
4
5
// 本地缩放
Vector3 scale = transform.localScale;

// 设置统一缩放
transform.localScale = Vector3.one * 2;

3.5 查找 GameObject

1
2
3
4
5
6
7
8
9
// 按名称查找(性能较差)
GameObject player = GameObject.Find("Player");

// 按标签查找
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");

// 按类型查找
PlayerController pc = FindObjectOfType<PlayerController>();
PlayerController[] allPcs = FindObjectsOfType<PlayerController>();

建议:运行时频繁查询应使用引用缓存,避免每帧 Find。


3.6 本章小结

  • GameObject 是容器,Component 是功能模块
  • 组合模式让 Unity 拥有极高的灵活性
  • Transform 是每个 GameObject 必有的组件
  • 使用 GetComponent<T>() 获取组件
  • 查找 GameObject 优先使用引用或标签

练习题

  1. 创建一个空对象作为 “Player”,添加 Cube 作为子级
  2. 通过脚本获取 Player 的 Transform,移动它并观察子级变化
  3. 在 Player 上添加 Rigidbody,运行并查看物理效果
  4. 练习 GetComponent / GetComponentInChildren 的使用
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
Unity3D开发基础教程 系列
第 3/20 篇
分享: