Unity 常用方法参考

方法名 调用时机 使用场景
Awake() 脚本实例被创建时首先调用 初始化变量、获取组件引用
Start() 在第一次Update之前调用 依赖其他组件的初始化
Update() 每帧调用一次 处理实时输入、连续移动
FixedUpdate() 固定时间间隔调用 物理相关计算
LateUpdate() 在所有Update之后调用 摄像机跟随、后期处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
private bool isGameStarted;

void Awake()
{
rb = GetComponent<Rigidbody>(); // 获取组件
}

void Start()
{
isGameStarted = true; // 游戏开始标志
}

void Update()
{
HandleInput(); // 处理玩家输入
}

void FixedUpdate()
{
if (isGameStarted)
{
MovePlayer(); // 物理移动
}
}

void LateUpdate()
{
CameraFollow(); // 摄像机更新
}
}

🔧 组件交互方法

获取组件

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

// 获取子对象组件
Collider childCollider = GetComponentInChildren<Collider>();

// 获取父对象组件
Transform parent = transform.parent;

// 查找对象(谨慎使用,性能开销大)
GameObject player = GameObject.Find("Player");
GameObject gameManager = GameObject.FindWithTag("GameController");

添加/删除组件

1
2
3
4
5
6
7
8
// 运行时添加组件
BoxCollider collider = gameObject.AddComponent<BoxCollider>();

// 禁用/启用组件
GetComponent<Renderer>().enabled = false;

// 删除组件
Destroy(GetComponent<BoxCollider>());

🎮 输入处理方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void HandleInput()
{
// 键盘输入
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");

// 按键检测
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}

if (Input.GetButton("Fire1"))
{
Shoot();
}

// 鼠标输入
if (Input.GetMouseButtonDown(0))
{
OnLeftClick();
}
}

📋 碰撞检测方法

方法名 触发条件 适用场景
OnCollisionEnter() 碰撞开始时 播放碰撞音效、计算伤害
OnCollisionStay() 碰撞持续中 持续伤害、摩擦效果
OnCollisionExit() 碰撞结束时 状态重置
OnTriggerEnter() 触发开始时 收集物品、进入区域
OnTriggerExit() 触发结束时 离开安全区
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class CollisionHandler : MonoBehaviour
{
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
TakeDamage(10);
}
}

void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Coin"))
{
CollectCoin(other.gameObject);
}
}

void CollectCoin(GameObject coin)
{
GameManager.Instance.AddScore(100);
Destroy(coin);
}
}

🎪 动画控制方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class AnimationController : MonoBehaviour
{
private Animator animator;

void Start()
{
animator = GetComponent<Animator>();
}

public void SetMovementAnimation(float speed)
{
animator.SetFloat("Speed", speed);
}

public void PlayJumpAnimation()
{
animator.SetTrigger("Jump");
}

public void SetBool(string name, bool value)
{
animator.SetBool(name, value);
}
}

⏰ 协程方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class TimedActions : MonoBehaviour
{
void Start()
{
StartCoroutine(SpawnEnemies());
}

IEnumerator SpawnEnemies()
{
while (true)
{
SpawnEnemy();
yield return new WaitForSeconds(2.0f); // 等待2秒
}
}

IEnumerator DestroyAfterDelay(GameObject obj, float delay)
{
yield return new WaitForSeconds(delay);
Destroy(obj);
}

IEnumerator FadeOut()
{
Renderer renderer = GetComponent<Renderer>();
Color color = renderer.material.color;

for (float alpha = 1f; alpha >= 0; alpha -= 0.1f)
{
color.a = alpha;
renderer.material.color = color;
yield return new WaitForSeconds(0.1f);
}
}
}

🏷️ 常用属性声明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class GameComponent : MonoBehaviour
{
// 在Inspector中显示,可在编辑器中调整
[Header("玩家设置")]
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float jumpForce = 10f;

[Space(10)]
[Header("引用")]
public GameObject projectilePrefab; // 公开变量自动显示在Inspector

// 范围滑块
[Range(0, 100)]
public int health = 100;

// 提示文本
[TextArea(3, 5)]
public string description;

// 序列化字段但不显示在Inspector
[System.NonSerialized]
public int temporaryValue;
}

🔄 常用事件方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class EventHandlers : MonoBehaviour
{
// 启用时调用
void OnEnable()
{
GameManager.OnGameStart += HandleGameStart;
}

// 禁用时调用
void OnDisable()
{
GameManager.OnGameStart -= HandleGameStart;
}

// 应用获得焦点
void OnApplicationFocus(bool hasFocus)
{
if (!hasFocus)
{
// 游戏暂停逻辑
}
}

// 应用退出
void OnApplicationQuit()
{
// 保存游戏数据
}

void HandleGameStart()
{
// 游戏开始处理
}
}

💡 实用技巧

使用[RequireComponent]确保依赖

1
2
3
4
5
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
// 会自动添加Rigidbody组件
}

缓存常用组件

1
2
3
4
5
6
7
8
private Rigidbody rb;
private Animator animator;

void Awake()
{
rb = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
}

使用Debug调试

1
2
3
4
5
void Update()
{
Debug.Log("玩家位置: " + transform.position);
Debug.DrawRay(transform.position, transform.forward * 5, Color.red);
}

Unity 常用方法参考
https://zuyue200.github.io/2025/10/11/unity-common-methods/
作者
zuyue200
发布于
2025年10月11日
更新于
2025年11月19日
许可协议