GameObject
GameObject 是 Unity 场景中最基本的存在单位——本身没有逻辑的空容器,所有行为都来自挂载的 Component。理解层级结构、激活状态以及 Tag 与 Layer,是搭建关卡、Prefab 与玩法对象的第一步,也是每个 Unity 初学者必须牢固掌握的核心场景、对象与组合式设计概念。
想象一下...
GameObject 就像舞台上没有剧本的演员。单独站着什么也做不了——Component(Rigidbody、Collider、Script…)才是服装、武器和剧本,让它真正行动起来。
概念详解
在 Unity 的 Entity-Component 架构中,
GameObject 就是 Entity——一个本身没有逻辑的身份。所有行为都来自挂载在其上的 Component。
每个 GameObject 都始终带有一个 Transform——无法移除的组件,负责位置、旋转和缩放。其他 Component 可通过 Inspector 中的 Add Component 添加。
GameObject 生活在树状 Hierarchy 中。移动 Parent 时,所有 Child 会一起移动——这让由许多部件组成的复杂角色能作为一个整体行动。
性能提示:GameObject.Find() 会遍历整个 Scene。务必在 Awake() 中
缓存引用并存入私有字段。
结构示意图
⚙ Transform
Position · Rotation · Scale
必需
⚙ Rigidbody
Mass · Drag · Gravity
⚙ Capsule Collider
Center · Radius · Height
⚙ PlayerCtrl (Script)
moveSpeed · jumpForce
Custom
动手步骤
创建新的 GameObject
Hierarchy → 右键 → Create Empty,或选择内置形状(Cube、Sphere…)。
命名并指定 Tag
在 Inspector 中命名(例如 Player),再指定 Tag,方便脚本更快查找。
挂载 Component
Inspector → Add Component → 添加 Rigidbody、Collider,再挂你的 C# 脚本。
在代码中使用
Instantiate() 克隆,FindWithTag() 查找,Destroy() 销毁。
交互模拟器
在 Hierarchy 中点击 GameObject 进行检查。尝试创建或销毁对象。
Hierarchy
← 选择一个 GameObject
代码示例
基础using UnityEngine;
public class GameObjectBasics : MonoBehaviour
{
public GameObject enemyPrefab;
void Start()
{
// Spawn an Enemy at (2, 0, 0)
GameObject newEnemy = Instantiate(enemyPrefab,
new Vector3(2f, 0f, 0f),
Quaternion.identity);
newEnemy.name = "Enemy_001";
// Find by Tag (faster than Find by name)
GameObject player = GameObject.FindWithTag("Player");
// Destroy the enemy after 5 seconds
Destroy(newEnemy, 5f);
}
}代码示例
进阶using UnityEngine;
public class GameObjectAdvanced : MonoBehaviour
{
[SerializeField] private GameObject bulletPrefab;
[SerializeField] private Transform firePoint;
// Cache components — avoid GetComponent() in Update
private Rigidbody _rb;
private Animator _anim;
void Awake()
{
_rb = GetComponent<Rigidbody>();
_anim = GetComponent<Animator>();
}
public void SpawnBullet()
{
if (bulletPrefab == null) return;
GameObject bullet = Instantiate(bulletPrefab,
firePoint.position, firePoint.rotation);
// Keep Hierarchy tidy: parent the bullet under a container
GameObject pool = GameObject.Find("BulletContainer");
if (pool != null) bullet.transform.SetParent(pool.transform);
// Disable without freeing memory
gameObject.SetActive(false);
}
}📌 快速记忆
- ▸GameObject = 空容器;行为来自 Component
- ▸每个 GO 都有 Transform——无法移除
- ▸
SetActive(false)隐藏对象但不释放内存 - ▸用 Tag 代替名字查找,更快
⚠️ 常见错误
❌ 在 Update() 里调用 GetComponent<>()
每帧都跑——代价极高
✅ 在 Awake() 中缓存到私有字段
❌ 在 Update() 里调用 GameObject.Find()
每帧遍历整个 Hierarchy
✅ 用 [SerializeField] 在 Editor 中拖引用