安利最简单易用的unity fsm有限状态机,以及推荐一些unity快捷脚本,快速创建c#文件

推荐插件

  1. autosave:unity商店直接搜,按时间自动保存(因为卡死丢了半天进度)
  2. RainbowFolders+RainbowHierarchy:unity文件夹也可以有图标和层级了,放在末尾的网盘
    在这里插入图片描述
  3. 一个脚本CreateCSharpScriptShortcut,可以按alt+n快速创建c#脚本,unity6需要改模版路径,一样放网盘
//  unity6之前
 string templatePath = System.IO.Path.Combine(editorPath, "Resources", "ScriptTemplates", "81-C# Script-NewBehaviourScript.cs.txt");

//unity6
string templatePath = System.IO.Path.Combine(editorPath, "Resources", "ScriptTemplates", "1-Scripting__MonoBehaviour Script-NewMonoBehaviourScript.cs.txt");
  1. SplitTexture:可以将切割好的素材生成完整的图片,平时处理素材很方便,具体参考:https://blog.csdn.net/linxinfa/article/details/114867642

有限状态机

10.21更新:在3d实践中验证了此状态机不适合复杂状态,依然可以处理简单的状态
原地址:https://github.com/thefuntastic/Unity3d-Finite-State-Machine

想要实现状态自动切换可以参考此教程:https://www.bilibili.com/video/BV1hy2PYpEvS

优点

使用简单,支持协程异步。不需要额外定义类型

缺点:

状态没有自己的属性,也不能继承,这里用状态集合进行替代,抽取公共的操作。对于单个类过长的问题,用分部类解决,状态之间用#region分割

更新
针对多个状态使用同一个动画的情况,使用抽象状态,只改变行为,不设置动画参数
添加了多个动画机的支持

网盘里的添加了ai生成的中文注释,并根据自己的动画模式进行了修改,约定枚举名为动画名,在切换时直接自动设置对应参数,极端情况只需要写枚举,一切都自动运行,没有一行重复的代码!(自我感觉可读性良好,也许不是?)
在这里插入图片描述

使用(仅关键代码):

public partial class Player : MonoBehaviour
{
    
    
    //约定动画名就是枚举名,我的改版会自动加载动画
    public enum States
    {
    
    
        Idle,
        Move,
        Jump,
        AirState,
        Dash,
        WallSlide,
        WallJump,
        PrimaryAttack,
    }
    private readonly HashSet<States> groundStates = new HashSet<States>() {
    
     States.Idle, States.Move };
    public StateMachine<States> fsm;

 private void Awake()
    {
    
    
        anim = GetComponentInChildren<Animator>();

        fsm = new StateMachine<States>(this, true);
        fsm.ChangeState(States.Idle);//立即调用enter
    }
    
private void Update()
    {
    
    
        //本该有个地面状态父类,统一处理,这里用状态组代替
        if (groundStates.Contains(fsm.CurrentState()))
        {
    
    
            if (!IsGround())
                fsm.ChangeState(States.AirState);

            //持续攻击
            if (hasAttackInput)
            {
    
    
                fsm.ChangeState(States.PrimaryAttack);
            }
        }

        //更新或自定义事件需要手动执行驱动器
        fsm.Driver.Update.Invoke();
        fsm.Driver.FixedUpdate.Invoke();
    }
}

//之后只要用枚举名_事件名的形式,就会自动触发
public partial class Player
{
    
    
    #region Idle
    void Idle_Enter()
    {
    
    
        ZeroVelocity();
    }
    void Idle_Exit()
    {
    
     }
    void Idle_Update()
    {
    
    
        if (xInput != 0 && !isBusy)
            fsm.ChangeState(States.Move);
    }
    #endregion
    
IEnumerator WallJump_Enter()
    {
    
    
        SetVelocity(5 * -facingDir, Tool.GetJumpForce(jumpHeight, rb) * 0.7f);
        yield return new WaitForSeconds(wallJumpDuration);
        fsm.ChangeState(States.AirState);
    }

结尾

链接:https://pan.baidu.com/s/1FdtwuFkH7yhWhVe-_MQJJQ?pwd=m2hi
提取码:m2hi