Unity 从零开始的框架搭建1-7 FSM有限状态机与其应用示例

本文小白可能看不懂,所以引路:​​​​​​【最用心 の Unity百宝箱】4. 有限状态机_哔哩哔哩_bilibili

当然,我不是按照小棋这么写的,但是思想都是一样的

另外说句题外话,配合动画状态机的函数用代码去控制逻辑才是真理,大量连线会导致项目无法维护,比如unity商店某Poly FPS PACKAGE里面的动画状态机

目录

1.单例基类

2.Mono代理

3.状态基类

4.状态机类

5.应用


1.单例基类

不懂单例模式?
C# & Unity 设计模式 之 单例模式_unity 使用单例做变量初始化-CSDN博客

cs 复制代码
using UnityEngine;

public class SingltonMono<T> : MonoBehaviour where T : SingltonMono<T>
{
    public static T Instance;
    protected virtual void Awake() 
    {
        if (Instance == null)
        {
            Instance = this as T;
        }
    }
}

2.Mono代理

看不懂Mono代理?

一言蔽之:让没有继承MonoBehaviour的类之中使用 MonoBehaviour 的 生命周期方法等

cs 复制代码
using System;

public class MonoManager : SingltonMono<MonoManager>
{
    private Action UpdateAction;
    private Action LaterUpdateAction;
    private Action FixedUpdateAction;

    public void AddUpdate(Action action)
    {
        UpdateAction += action;
    }

    public void AddLaterUpdate(Action action)
    {
        LaterUpdateAction += action;
    }
    public void AddFixedUpdate(Action action)
    {
        FixedUpdateAction += action;
    }

    public void RemoveUpdate(Action action)
    {
        UpdateAction -= action;
    }
    public void RemoveLaterUpdate(Action action)
    {
        LaterUpdateAction -= action;
    }
    public void RemoveFixedUpdate(Action action)
    {
        FixedUpdateAction -= action;
    }

    private void Update()
    {
        UpdateAction?.Invoke();
    }
    private void LateUpdate()
    {
        LaterUpdateAction?.Invoke();
    }
    private void FixedUpdate()
    {
        FixedUpdateAction?.Invoke();
    }

}

3.状态基类

看不懂状态基类?

我不信你看不懂,这都看不懂就滚去学oop!

C# & Unity 面向对象补全计划 之 初识继承方法与多态(干货)_unity 继承-CSDN博客

cs 复制代码
public abstract class StateBase
{
    public virtual void Init(IStateMachineOwner owner) { }
    public virtual void UnInit() { }
    public virtual void Enter() { }
    public virtual void Exit() { }
    public virtual void Update() { }
    public virtual void LateUpdate() { }
    public virtual void FixedUpdate()
    {
    }
}

4.状态机类

IStateMachineOwner接口利用了里氏替换

C# & Unity 面向对象补全计划 七大原则 之 里氏替换(LSP) 难度:☆☆☆ 总结:子类可以当父类用,牛马是马,骡马也是马-CSDN博客

以及类似控制反转的方式(看下文高级使用实例)

C# & Unity 面向对象补全计划 之 接口_unity c# 接口-CSDN博客

cs 复制代码
using System;
using System.Collections.Generic;

public interface IStateMachineOwner
{
}
public class StateMechine
{
    private IStateMachineOwner owner; //Any Class can be onwner only inherit this interface
    private Dictionary<Type, StateBase> statesDic = new Dictionary<Type, StateBase>();
    public StateBase currentStateBase;

    public Type CurrentStateType => currentStateBase?.GetType();
    public bool HasState => currentStateBase != null;

    //初始化状态机
    public void Init(IStateMachineOwner owner)
    {
        this.owner = owner;
    }
    //切换状态
    public bool ChangeState<T>(bool needRewState = false) where T : StateBase, new()
    {
        //check state is consistent
        if (HasState && CurrentStateType == typeof(T) && !needRewState) return false;

        //exit
        if (currentStateBase != null)
        {
            currentStateBase.Exit();
            MonoManager.Instance.RemoveFixedUpdate(currentStateBase.Update);
            MonoManager.Instance.RemoveLaterUpdate(currentStateBase.LateUpdate);
            MonoManager.Instance.RemoveUpdate(currentStateBase.Update);
        }

        currentStateBase = GetState<T>();
        currentStateBase.Enter();
        MonoManager.Instance.AddUpdate(currentStateBase.Update);
        MonoManager.Instance.AddLaterUpdate(currentStateBase.LateUpdate);
        MonoManager.Instance.AddFixedUpdate(currentStateBase.FixedUpdate);

        return false;
    }
    //获取状态
    public StateBase GetState<T>() where T : StateBase, new()
    {
        if (!statesDic.TryGetValue(typeof(T), out StateBase TryState))
        {
            T t = new T();
            t.Init(owner);
            statesDic.Add(typeof(T), t);
            TryState = t;
        }
        return TryState;
    }
    //停止状态机
    public void Stop()
    {
        currentStateBase.Exit();
        MonoManager.Instance.RemoveUpdate(currentStateBase.Update);
        MonoManager.Instance.RemoveLaterUpdate(currentStateBase.LateUpdate);
        MonoManager.Instance.RemoveFixedUpdate(currentStateBase.FixedUpdate);
        currentStateBase = null;

        foreach (var item in statesDic.Values)
        {
            item.UnInit();
        }
        statesDic.Clear();
    }
}

5.应用

所示工程文件链接如下,因为我比较菜 所以填了一些坑 花了一下午才写这么点功能实在惭愧:

通过网盘分享的文件:Assets.7z链接: https://pan.baidu.com/s/1yqALCXDFgDnb7Trs2181EQ?pwd=1234 提取码: 1234

视频请看这个

状态机应用

我b站好像也发了

分享一下最近的想法_哔哩哔哩_bilibili

相关推荐
徐子竣2 小时前
[学习记录]Unity-Shader-几何着色器
unity·游戏引擎·着色器
EQ-雪梨蛋花汤7 小时前
【Part 3 Unity VR眼镜端播放器开发与优化】第四节|高分辨率VR全景视频播放性能优化
unity·音视频·vr
江山如画,佳人北望11 小时前
C#程序入门
开发语言·windows·c#
与火星的孩子对话12 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
future141212 小时前
C#每日学习日记
java·学习·c#
幻世界13 小时前
【Unity智能模型系列】Unity + MediaPipe + Sentis + ArcFace模型:构建高效人脸识别比对系统
unity·游戏引擎
军训猫猫头15 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
漫游者Nova20 小时前
虚幻引擎Unreal Engine5恐怖游戏设计制作教程,从入门到精通从零开始完整项目开发实战详细讲解中英字幕
ue5·游戏引擎·虚幻·游戏开发完整教程·恐怖游戏开发
死也不注释1 天前
【Unity 编辑器工具开发:GUILayout 与 EditorGUILayout 对比分析】
unity·编辑器·游戏引擎
葬歌倾城1 天前
JSON的缩进格式方式和紧凑格式方式
c#·json