简易的状态机代码
PlayerState.cs
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerState
{
protected PlayerStateMachine stateMachine;
protected Player player;
private string animBoolName;
public PlayerState(PlayerStateMachine stateMachine, Player player, string animBoolName)
{
this.stateMachine = stateMachine;
this.player = player;
this.animBoolName = animBoolName;
}
public virtual void Enter()
{
Debug.Log("I enter " + animBoolName);
}
public virtual void Update()
{
Debug.Log("I'm in " + animBoolName);
}
public virtual void Exit()
{
Debug.Log("I exit " + animBoolName);
}
}
PlayerIdleState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerIdleState : PlayerState
{
public PlayerIdleState(PlayerStateMachine stateMachine, Player player, string animBoolName) : base(stateMachine, player, animBoolName)
{
}
public override void Enter()
{
base.Enter();
}
public override void Exit()
{
base.Exit();
}
public override void Update()
{
base.Update();
if (Input.GetKeyDown(KeyCode.N))
stateMachine.ChangeState(player.moveState);
}
}
PlayerMoveState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMoveState : PlayerState
{
public PlayerMoveState(PlayerStateMachine stateMachine, Player player, string animBoolName) : base(stateMachine, player, animBoolName)
{
}
public override void Enter()
{
base.Enter();
}
public override void Exit()
{
base.Exit();
}
public override void Update()
{
base.Update();
if (Input.GetKeyDown(KeyCode.N))
stateMachine.ChangeState(player.idleState);
}
}
PlayerStateMachine.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerStateMachine
{
public PlayerState currentState { get; private set; }
public void Initiallize(PlayerState _startState)
{
currentState = _startState;
currentState.Enter();
}
public void ChangeState(PlayerState _newState)
{
currentState.Exit();
currentState = _newState;
currentState.Enter();
}
}
Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public PlayerStateMachine stateMachine { get; private set; }
public PlayerIdleState idleState { get; private set; }
public PlayerMoveState moveState { get; private set; }
private void Awake()
{
stateMachine = new PlayerStateMachine();
idleState = new PlayerIdleState(stateMachine, this, "Idle");
moveState = new PlayerMoveState(stateMachine, this, "Move");
}
private void Start()
{
stateMachine.Initiallize(idleState);
}
private void Update()
{
stateMachine.currentState.Update();
}
}