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>();
Destroy(GetComponent<BoxCollider>());
Collider collider = GetComponent<Collider>(); collider.enabled = false;
|
位置
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);
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 优先使用引用或标签
练习题
- 创建一个空对象作为 “Player”,添加 Cube 作为子级
- 通过脚本获取 Player 的 Transform,移动它并观察子级变化
- 在 Player 上添加 Rigidbody,运行并查看物理效果
- 练习
GetComponent / GetComponentInChildren 的使用