Enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
//以下全为受保护的对象
//设置可读属性
public Rigidbody2D rb{ get; private set; }//定义刚体组件
public Animator anim { get; private set; }//定义动画组件
public EnemyStateMachine stateMachine { get; private set; }//定义敌人状态机类
//唤醒控制器
private void Awake()
{
stateMachine = new EnemyStateMachine();//创建敌人状态机类
}
//持续更新敌人配置
private void Update()
{
stateMachine.currentState.Update();
}
}
EnemyState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyState
{
//定义状态机
protected EnemyStateMachine stateMacine;
//敌人
protected Enemy enemy;
//触发器
protected bool triggerCalled;
//动画名:改变动画状态会使用
private string animBoolName;
//计时器
protected float stateTimer;
//构造函数:框架
public EnemyState(EnemyStateMachine _stateMacine, Enemy _enemy, string _animBoolName)
{
this.stateMacine = _stateMacine;
this.enemy = _enemy;
this.animBoolName =_animBoolName;
}
public virtual void Update()
{
stateTimer = -Time.deltaTime;
}
public virtual void Enter()
{
triggerCalled = false;
enemy.anim.SetBool(animBoolName, true);//开始当前动画
}
public virtual void Exit()
{
enemy.anim.SetBool(animBoolName, false);//结束当前动画
}
}
EnemyStateMachine.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyStateMachine : MonoBehaviour
{
public EnemyState currentState { get; private set; }//通过敌人状态类定义当前状态类
public void Initialize(EnemyState _startState)//初始化状态的函数
{
currentState = _startState;
currentState.Enter();
}
public void ChangeState(EnemyState _newState)//改变状态函数
{
currentState.Exit();
currentState = _newState;
currentState.Enter();
}
}