C# Unity FSM 状态机

C# Unity FSM 状态机

使用状态机可以降低代码耦合性,并且可以优化代码可读性,方便团队协作等。
对于游戏开发内容来讲游戏开发的流程控制玩家动画都可以使用FSM有限状态机来实现。

1.FsmState

每个状态的基类,泛型参数表示所拥有者

public abstract class FsmState<T> where T : class
{protected internal abstract void OnInit(IFsm<T> fsm);protected internal abstract void OnEnter(IFsm<T> fsm);protected internal abstract void OnUpdate(IFsm<T> fsm);protected internal abstract void OnLeave(IFsm<T> fsm);protected internal abstract void OnDestroy(IFsm<T> fsm);protected void ChangeState<TState>(IFsm<T> fsm) where TState : FsmState<T>{Fsm<T> fsmImplement = (Fsm<T>)fsm;if(fsmImplement == null){throw new Exception("FSM is invalid.");}fsmImplement.ChangeState<TState>();}protected void ChangeState(IFsm<T> fsm, Type stateType){Fsm<T> fsmImplement = (Fsm<T>)fsm;if (fsmImplement == null){throw new Exception("FSM is invalid.");}if (stateType == null){throw new Exception("State type is invalid.");}if (!typeof(FsmState<T>).IsAssignableFrom(stateType)){throw new Exception("State type is invalid.");}fsmImplement.ChangeState(stateType);}
}

2.IFsm

有限状态机的接口

public interface IFsm<T> where T : class
{string Name{get;}string FullName{get;}T Owner{get;}int FsmStateCount{get;}bool IsRunning{get;}bool IsDestroyed{get;}FsmState<T> CurrentState{get;}float CurrentStateTime{get;}void Start<TState>() where TState : FsmState<T>;bool HasState<TState>() where TState : FsmState<T>;TState GetState<TState>() where TState : FsmState<T>;FsmState<T> GetState(Type stateType);FsmState<T>[] GetAllStates();
}

3.IFsmManager

有限状态机管理器接口

public interface IFsmManager
{int Count { get; }bool HasFsm<T>() where T : class;bool HasFsm(Type ownerType);bool HasFsm<T>(string name) where T : class;bool HasFsm(Type ownerType, string name);IFsm<T> GetFsm<T>() where T : class;IFsm<T> GetFsm<T>(string name) where T : class;IFsm<T> CreateFsm<T>(T owner, params FsmState<T>[] fsmStates) where T : class;IFsm<T> CreateFsm<T>(string name, T owner, params FsmState<T>[] states) where T : class;IFsm<T> CreateFsm<T>(T owner, List<FsmState<T>> states) where T : class;IFsm<T> CreateFsm<T>(string name, T owner, List<FsmState<T>> states) where T : class;bool DestroyFsm<T>() where T : class;bool DestroyFsm(Type ownerType);bool DestroyFsm<T>(string name) where T : class;bool DestroyFsm(Type ownerType, string name);bool DestroyFsm<T>(IFsm<T> fsm) where T : class;
}

4.FsmBase

有限状态机的基类

public abstract class FsmBase
{private string m_Name;public FsmBase(){m_Name = string.Empty;}public string Name{get{return m_Name;}protected set{m_Name = value ?? string.Empty;}}public string FullName{get{return $"{OwnerType.FullName}.{Name}";}}public abstract Type OwnerType{get;}public abstract int FsmStateCount{get;}public abstract bool IsRunning{get;}public abstract bool IsDestroyed{get;}public abstract string CurrentStateName{get;}public abstract float CurrentStateTime{get;}public abstract void Update();public abstract void Shutdown();
}

5.Fsm

状态机类

public class Fsm<T> : FsmBase, IFsm<T> where T : class
{private T m_Owner;private readonly Dictionary<Type, FsmState<T>> m_States;private FsmState<T> m_CurrentState;private float m_CurrentStateTime;private bool m_IsDestroyed;public Fsm(){m_Owner = null;m_States = new Dictionary<Type, FsmState<T>>();m_CurrentState = null;m_CurrentStateTime = 0f;m_IsDestroyed = true;}public T Owner => m_Owner;public FsmState<T> CurrentState => m_CurrentState;public override Type OwnerType => typeof(T);public override int FsmStateCount => m_States.Count;public override bool IsRunning => m_CurrentState != null;public override bool IsDestroyed => m_IsDestroyed;public override string CurrentStateName => m_CurrentState != null ? m_CurrentState.GetType().FullName : null;public override float CurrentStateTime => m_CurrentStateTime;public static Fsm<T> Create(string name,T owner,params FsmState<T>[] states){if(owner == null){throw new Exception("FSM owner is invalid.");}if(states== null|| states.Length < 1){throw new Exception("FSM states is invalid.");}Fsm<T> fsm = Pool<Fsm<T>>.Rent();fsm.Name = name;fsm.m_Owner = owner;fsm.m_IsDestroyed = false;foreach (FsmState<T> oneState in states){if(oneState == null){throw new Exception("FSM states is invalid.");}Type stateType = oneState.GetType();if (fsm.m_States.ContainsKey(stateType)){throw new Exception($"{stateType} state is already exist");}fsm.m_States.Add(stateType, oneState);oneState.OnInit(fsm);}return fsm;}public static Fsm<T> Create(string name,T owner,List<FsmState<T>> states){if (owner == null){throw new Exception("FSM owner is invalid.");}if (states == null || states.Count < 1){throw new Exception("FSM states is invalid.");}Fsm<T> fsm = Pool<Fsm<T>>.Rent();fsm.Name = name;fsm.m_Owner = owner;fsm.m_IsDestroyed = false;foreach (FsmState<T> oneState in states){if (oneState == null){throw new Exception("FSM states is invalid.");}Type stateType = oneState.GetType();if (fsm.m_States.ContainsKey(stateType)){throw new Exception($"{stateType} state is already exist");}fsm.m_States.Add(stateType, oneState);oneState.OnInit(fsm);}return fsm;}public FsmState<T>[] GetAllStates(){int index = 0;FsmState<T>[] arr = new FsmState<T>[m_States.Count];foreach (FsmState<T> fsmState in m_States.Values){arr[index++] = fsmState;}return arr;}public bool HasState<TState>() where TState : FsmState<T>{return m_States.ContainsKey(typeof(TState));}public override void Shutdown(){Pool<Fsm<T>>.Return(this, (fsm) =>{if(m_CurrentState != null){m_CurrentState.OnLeave(this);}foreach (FsmState<T> oneState in m_States.Values){oneState.OnDestroy(this);}Name = null;m_Owner = null;m_States.Clear();m_CurrentState = null;m_CurrentStateTime = 0f;m_IsDestroyed = true;});}public void Start<TState>() where TState : FsmState<T>{if (IsRunning){throw new Exception("FSM is running, can not start again.");}FsmState<T> state = GetState<TState>();if (state == null){throw new Exception("can not start state");}m_CurrentStateTime = 0f;m_CurrentState = state;m_CurrentState.OnEnter(this);}public void Start(Type stateType){if (IsRunning){throw new Exception("FSM is running, can not start again.");}if (stateType == null){throw new Exception("State type is invalid.");}if (!typeof(FsmState<T>).IsAssignableFrom(stateType)){throw new Exception("State type is invalid.");}FsmState<T> state = GetState(stateType);if (state == null){throw new Exception("FSM can not start state which is not exist.");}m_CurrentStateTime = 0f;m_CurrentState = state;m_CurrentState.OnEnter(this);}public override void Update(){m_CurrentStateTime += Time.deltaTime;m_CurrentState.OnUpdate(this);}public TState GetState<TState>() where TState : FsmState<T>{if (m_States.TryGetValue(typeof(TState), out FsmState<T> fsmState)){return (TState)fsmState;}return null;}public FsmState<T> GetState(Type stateType){if (stateType == null){throw new Exception("State type is invalid.");}if (!typeof(FsmState<T>).IsAssignableFrom(stateType)){throw new Exception("State type is invalid.");}if (m_States.TryGetValue(stateType, out FsmState<T> fsmState)){return fsmState;}return null;}public void ChangeState<TState>(){ChangeState(typeof(TState));}public void ChangeState(Type stateType){if (m_CurrentState == null){throw new Exception("Current state is invalid.");}FsmState<T> state = GetState(stateType);if (state == null){throw new Exception("FSM can not change state which is not exist.");}m_CurrentState.OnLeave(this);m_CurrentStateTime = 0f;m_CurrentState = state;m_CurrentState.OnEnter(this);}
}

6.FsmManager

状态机管理器

public class FsmManager : Singleton<FsmManager>,IFsmManager,IUpdateSingleton
{private readonly Dictionary<string, FsmBase> m_FsmDic;private readonly List<FsmBase> m_TempFsms;public FsmManager(){m_FsmDic = new Dictionary<string, FsmBase>();m_TempFsms = new List<FsmBase>();}public int Count => m_FsmDic.Count;public IFsm<T> CreateFsm<T>(T owner, params FsmState<T>[] fsmStates) where T : class{return CreateFsm(string.Empty, owner, fsmStates);}public IFsm<T> CreateFsm<T>(string name, T owner, params FsmState<T>[] states) where T : class{if (HasFsm<T>(name)){throw new Exception("Already exist FSM");}Fsm<T> fsm = Fsm<T>.Create(name, owner, states);m_FsmDic.Add(fsm.FullName, fsm);return fsm;}public IFsm<T> CreateFsm<T>(T owner, List<FsmState<T>> states) where T : class{return CreateFsm(string.Empty, owner, states);}public IFsm<T> CreateFsm<T>(string name, T owner, List<FsmState<T>> states) where T : class{if (HasFsm<T>(name)){throw new Exception("Already exist FSM");}Fsm<T> fsm = Fsm<T>.Create(name, owner, states);m_FsmDic.Add(fsm.FullName, fsm);return fsm;}public bool DestroyFsm<T>() where T : class{return InternalDestroyFsm($"{typeof(T).FullName}.{string.Empty}");}public bool DestroyFsm(Type ownerType){if (ownerType == null){throw new Exception("Owner type is invalid.");}return InternalDestroyFsm($"{ownerType.FullName}.{string.Empty}");}public bool DestroyFsm<T>(string name) where T : class{return InternalDestroyFsm($"{typeof(T).FullName}.{name}");}public bool DestroyFsm(Type ownerType, string name){if (ownerType == null){throw new Exception("Owner type is invalid.");}return InternalDestroyFsm($"{ownerType.FullName}.{name}");}public bool DestroyFsm<T>(IFsm<T> fsm) where T : class{if (fsm == null){throw new Exception("FSM is invalid.");}return InternalDestroyFsm(fsm.FullName);}public IFsm<T> GetFsm<T>() where T : class{return (IFsm<T>)InternalGetFsm($"{typeof(T).FullName}.{string.Empty}");}public IFsm<T> GetFsm<T>(string name) where T : class{return (IFsm<T>)InternalGetFsm($"{typeof(T).FullName}.{name}");}public bool HasFsm<T>() where T : class{return InternalHasFsm($"{typeof(T).FullName}.{string.Empty}");}public bool HasFsm(Type ownerType){if(ownerType == null){throw new Exception("Owner type is invalid.");}return InternalHasFsm($"{ownerType.FullName}.{string.Empty}");}public bool HasFsm<T>(string name) where T : class{return InternalHasFsm($"{typeof(T).FullName}.{name}");}public bool HasFsm(Type ownerType, string name){if (ownerType == null){throw new Exception("Owner type is invalid.");}return InternalHasFsm($"{ownerType.FullName}.{name}");}private bool InternalDestroyFsm(string name){if(m_FsmDic.TryGetValue(name,out FsmBase fsmBase)){fsmBase.Shutdown();return m_FsmDic.Remove(name);}return false;}private FsmBase InternalGetFsm(string name){FsmBase fsm = null;if (m_FsmDic.TryGetValue(name, out fsm)){return fsm;}return null;}private bool InternalHasFsm(string name){return m_FsmDic.ContainsKey(name);}public void Update(){m_TempFsms.Clear();if (m_FsmDic.Count <= 0)return;foreach (FsmBase fsmBase in m_FsmDic.Values){m_TempFsms.Add(fsmBase);}foreach (FsmBase fsmBase in m_TempFsms){if (fsmBase.IsDestroyed)continue;fsmBase.Update();}}protected override void Load(int assemblyName){}protected override void UnLoad(int assemblyName){}
}

7.测试

(一)IdleState

public class IdleState : FsmState<FsmTest>
{protected internal override void OnDestroy(IFsm<FsmTest> fsm){Debug.Log("销毁 IdleState");}protected internal override void OnEnter(IFsm<FsmTest> fsm){Debug.Log("进入 IdleState");}protected internal override void OnInit(IFsm<FsmTest> fsm){}protected internal override void OnLeave(IFsm<FsmTest> fsm){Debug.Log("离开 IdleState");}protected internal override void OnUpdate(IFsm<FsmTest> fsm){if (Input.GetKeyDown(KeyCode.A)){ChangeState<WalkState>(fsm);}}
}

(二)WalkState

public class WalkState : FsmState<FsmTest>
{protected internal override void OnDestroy(IFsm<FsmTest> fsm){Debug.Log("销毁 WalkState");}protected internal override void OnEnter(IFsm<FsmTest> fsm){Debug.Log("进入 WalkState");}protected internal override void OnInit(IFsm<FsmTest> fsm){}protected internal override void OnLeave(IFsm<FsmTest> fsm){Debug.Log("离开 WalkState");}protected internal override void OnUpdate(IFsm<FsmTest> fsm){if (Input.GetKeyDown(KeyCode.B)){ChangeState<RunState>(fsm);}}
}

(三)RunState

public class RunState : FsmState<FsmTest>
{protected internal override void OnDestroy(IFsm<FsmTest> fsm){Debug.Log("销毁 RunState");}protected internal override void OnEnter(IFsm<FsmTest> fsm){Debug.Log("进入 RunState");}protected internal override void OnInit(IFsm<FsmTest> fsm){}protected internal override void OnLeave(IFsm<FsmTest> fsm){Debug.Log("离开 RunState");}protected internal override void OnUpdate(IFsm<FsmTest> fsm){if (Input.GetKeyDown(KeyCode.C)){ChangeState<IdleState>(fsm);}}
}

mono测试

public class FsmTest : MonoBehaviour
{private IFsm<FsmTest> m_TestFsm;void Start(){SingletonSystem.Initialize();AssemblyManager.Load(1, GetType().Assembly);m_TestFsm = FsmManager.Instance.CreateFsm<FsmTest>("MyTestFsm",this, new IdleState(),new WalkState(),new RunState());m_TestFsm.Start<IdleState>();}void Update(){SingletonSystem.Update();if (Input.GetKeyDown(KeyCode.P)){FsmManager.Instance.DestroyFsm(m_TestFsm);}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/76561.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

轻松搭建本地知识库的ChatGLM2-6B

近期发现了一个项目&#xff0c;它的前身是ChatGLM&#xff0c;在我之前的博客中有关于ChatGLM的部署过程&#xff0c;本项目在前者基础上进行了优化&#xff0c;可以基于当前主流的LLM模型和庞大的知识库&#xff0c;实现本地部署自己的ChatGPT&#xff0c;并可结合自己的知识…

GC 算法与种类

对于垃圾收集&#xff08;GC&#xff09;, 我们需要考虑三件事情&#xff1a;哪些内存需要回收&#xff1f;如何判断是垃圾对象&#xff1f;垃圾回收算法有哪些&#xff1f; 一、GC的工作区域 1、不是GC的工作区域 (1)程序计数器、虚拟机栈和本地方法栈三个区域是线程私有的&…

python excel 读取及写入固定格式

import xlrd import xlwt import re import pandas as pd from datetime import date,datetimefile_path "C:\\Users\\function_model.xls" def readexcel():df pd.read_excel(file_path ,"配置")# e_id# id# expression# name# freq# column_data df[e…

yolov8 模型部署--TensorRT部署-c++服务化部署

写目录 yolov8 模型部署--TensorRT部署1、模型导出为onnx格式2、模型onnx格式转engine 部署 yolov8 模型部署–TensorRT部署 1、模型导出为onnx格式 如果要用TensorRT部署YOLOv8&#xff0c;需要先使用下面的命令将模型导出为onnx格式&#xff1a; yolo export modelyolov8n.p…

FPGA时序分析与约束(2)——时序电路时序

一、前言 在之前的内容中&#xff0c;我们介绍了组合电路的时序问题和可能导致的毛刺&#xff0c;强烈推荐在阅读前文的基础上再继续阅读本文&#xff0c; 前文链接&#xff1a;FPGA时序分析与约束&#xff08;1&#xff09;——组合电路时序 这篇文章中&#xff0c;我们将继续…

解决微信小程序动态生成表单情况下,遍历picker,并无法修改列表里面下标key的解决访方案

需求描述&#xff1a; 通过请求后端接口&#xff0c;动态获取表单的数据源&#xff08;json格式&#xff0c;数组&#xff09;&#xff0c;使用小程序wx:for循环遍历&#xff0c;对接口返回的数组中的一个字段存为picker组件选择器&#xff0c;并允许用户进行选择修改该值。 …

MySQL表空间

MySQL表空间 文章目录 MySQL表空间1. MySQL中的表1.1 IOT表1.2 InnoDB逻辑存储结构2. 独立表空间2.1 段 segment2.1.1 段的概念2.1.2 段的分类2.1.2.1 叶子节点段主要结构2.1.2.2 非叶子节点段2.1.3 碎片区2.2 区2.2.1 区的概念2.2.2 区的结构2.2.2.1 XDES Entry结构2.3 页2.3.…

tpwe兼容微擎小程序前端请求写法

当使用TPWe兼容微擎小程序前端时&#xff0c;可以按照以下方式编写前端请求&#xff1a; 修改siteinfo.js下面的配置文件。 var e {uniacid: "10001",acid: "10001",multiid: "0",version: "1.0",siteroot: "https://域名/inde…

基于51单片机的称重电子秤proteus仿真设计

一、设计背景 随着微电子技术的应用,市场上使用的传统称重工具已经满足不了人们的要求。为了改变传统称重工具在使用上存在的问题&#xff0c;在本设计中将智能化、自动化、人性化用在了电子秤重的控制系统中。本系统主要由单片机来控制&#xff0c;测量物体重量部分使用称重传…

springCloud bean的加载流程

Spring Cloud是Spring的一个子项目&#xff0c;用于构建基于Spring Boot的分布式系统。在Spring Cloud中&#xff0c;Bean的加载过程与Spring框架的Bean加载过程相似&#xff0c;主要包括以下几个步骤&#xff1a; 1、读取配置文件&#xff1a;Spring Cloud从配置文件中加载Be…

Activiti7工作流引擎:在线流程编辑器Activiti Modoler5.x

一&#xff1a;简介 有的时候我们的流程图需要业务人员自己绘制&#xff0c;然后使用自己绘制的流程图&#xff0c;此时就需要一个在线流程图编辑器需要集成到我们的web系统中。Activiti Modoler是Activiti官方推出的在线流程编辑器。 二&#xff1a;pom.xml <dependency…

飞书公式总结

文本处理函数 飞书中的表格&#xff0c;需要实现 内容内容1条件1内容2条件2内容3条件3今天是周一;可以出去玩今天是周一能今天天气不错不能可以出去玩能 条件1&#xff0c;2&#xff0c;3为能时&#xff0c;把对应的内容1&#xff0c;内容2&#xff0c;内容3复制到内容 TEX…

Golang项目实战(三)

Golang项目实战&#xff08;三&#xff09; 该项目是使用grpcgin来构建的一个电商微服务项目&#xff0c;使用consul来注册和发现微服务。 项目简介创建项目架构创建货币服务创建货币微服务处理器将货币微服务注册到consul下载安装consul并发布服务创建商品微服务准备商品数据…

HNU小学期工训-STC15单片机模型大作业实验报告

STC15单片机模型大作业实验报告 全称&#xff1a;基于STC15单片机与OLED显示模块&PC端演示的多功能声光温振时钟智能手表模型 计科210X 甘晴void 202108010XXX 【请注意&#xff1a;本作业入选优秀范例&#xff0c;直接照抄源码有很大风险】 【建议理解原理之后作改动】 …

基于SSM框架的德云社票务系统

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用Vue技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

C#之位运算

符号&#xff1a;<< >> & | ^ ~ 作用&#xff1a;用于二进制数据的操作 表达式&#xff1a; 表达式 运算符 表达式 ~表达式或者是变量 优先级&#xff1a;~高于<< , >> 高于 & 高于 | ^ 结合性&#xff1a;左结合 说明&#xff1…

2024届校招-Java开发笔试题-S4卷

有三种题型&#xff1a;单项选择题&#xff08;10道&#xff09;、不定项选择题&#xff08;10道&#xff09;、编程题&#xff08;3道&#xff09; 下面是一些回忆的题目&#xff1a; 1.哪种设计模式将对象的创建与使用分离&#xff0c;通过工厂类创建对象 答&#xff1a;工…

Linux入门教程||Linux系统目录结构

登录系统后&#xff0c;在当前命令窗口下输入命令&#xff1a; ls / 你会看到如下图所示: 树状目录结构&#xff1a; 以下是对这些目录的解释&#xff1a; /bin&#xff1a; bin是Binary的缩写, 这个目录存放着最经常使用的命令。 /boot&#xff1a; 这里存放的是启动Linux时…

RP9学习-1

一.基础 1.10个面板位置示意图&#xff1a; 2.常用英文 1.鼠标点击&#xff1a;click or tap 3.工作区 1.恢复默认工作区&#xff1a; view-->reset view 2.自定义工作区&#xff1a; 可以用鼠标左键拖动面板到独立的位置或者吸附到其他面板上 3.自定义工具栏 view-->T…

优漫动游 常见的AI视频生成网站的官方网站:

1、Lumen5 Lumen5是一款在线视频制作工具&#xff0c;利用人工智能技术能够迅速将文本、和音乐转换为视频。它可以帮助你把博客文章、社交媒体内容等转化为吸引人的视频&#xff0c;从而提高你的品牌曝光率和社交媒体的参与度。 2.Animoto Animoto是一个视频制作平台&…