2026.05.15
游戏开发中的状态机设计模式
## 状态机模式
状态机(State Machine)是游戏开发中最常用的设计模式之一。
### 为什么需要状态机?
游戏中的角色通常有多种状态:待机、行走、攻击、受伤、死亡等。如果没有好的管理模式,代码会变成一堆 if-else 判断,难以维护。
### 实现方式
#### 方式一:枚举 + Switch
```csharp
public enum PlayerState { Idle, Walk, Attack, Hurt, Die }
public class Player : MonoBehaviour {
public PlayerState currentState;
void Update() {
switch (currentState) {
case PlayerState.Idle: /* ... */ break;
case PlayerState.Walk: /* ... */ break;
// 每个状态都要处理,代码会越来越长
}
}
}
```
#### 方式二:状态类(推荐)
```csharp
public abstract class PlayerStateBase {
public abstract void Enter(Player player);
public abstract void Update(Player player);
public abstract void Exit(Player player);
}
public class PlayerIdleState : PlayerStateBase {
public override void Enter(Player player) {
player.animator.Play("Idle");
}
public override void Update(Player player) {
if (Input.GetAxis("Horizontal") != 0)
player.stateMachine.ChangeState(new PlayerWalkState());
}
public override void Exit(Player player) { }
}
```
### 总结
状态机模式让游戏逻辑更清晰、更易维护。建议使用状态类的方式实现,而不是单纯的枚举 + switch。