内容纲要

状态机的主代码:

StatMachine.cs(状态机)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

///<summary>
///
///</summary>
public class StateMachine<TOwner> : MonoBehaviour
{
    private State<TOwner> curState = null;
    private TOwner owner;//状态机的拥有者

    public void Init(TOwner _owner ,State <TOwner > initialState)//初始状态
    {
        this.owner = _owner;
        ChangeState(initialState);
    }

    public void ChangeState(State <TOwner> newState)//转换状态
    {
        //print(string.Format("{0}=>{1}", curState == null ? "n/a" : curState.GetType().Name, newState.GetType().Name));
        if (curState != null)
        {
            curState.Exit(owner);//清理
        }
        curState = newState;
        curState.Enter(owner);//初始化
    }

    public void Update()
    {
        curState.Update(owner);
    }
}

State.cs(状态)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

///<summary>
///
///</summary>
public class State<TOwner> : MonoBehaviour
{
    public virtual void Enter(TOwner e)
    {

    }

    public virtual  void  Update(TOwner e)
    {

    }

    public  virtual void Exit(TOwner e)
    {

    }
}

自己对状态机的理解:

状态机的本质是一种类,通过嵌套多个类来表示游戏AI的不同的状态时所展现的行为方式(如初始模式,巡逻模式,攻击模式,逃跑模式等等)。通过不同的条件来调用所需的类。

发表评论