Unity资源管理系统 ——YooAsset学习笔记(二)有限状态机管理器FsmManager

YooAsset学习笔记系列

什么是YooAsset:https://github.com/tuyoogame/YooAsset/tree/main
事件管理器EventManager
有限状态机管理器FsmManager


文章目录

  • YooAsset学习笔记系列
  • 前言


前言

一个比较简单的有限状态机,直接在代码里加注释了。

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

/// 
/// 有限状态机
/// 
public static class FsmManager
{
	// 所有的状态节点
	private static readonly List<IFsmNode> _nodes = new List<IFsmNode>();
	// 当前运行状态节点
	private static IFsmNode _curNode;
	// 上一个运行的状态节点
	private static IFsmNode _preNode;

	/// 
	/// 当前运行的节点名称
	/// 
	public static string CurrentNodeName
	{
		get { return _curNode != null ? _curNode.Name : string.Empty; }
	}

	/// 
	/// 之前运行的节点名称
	/// 
	public static string PreviousNodeName
	{
		get { return _preNode != null ? _preNode.Name : string.Empty; }
	}


	/// 
	/// 启动状态机
	/// 
	/// 入口节点
	public static void Run(string entryNode)
	{
		_curNode = GetNode(entryNode);
		_preNode = GetNode(entryNode);

		if (_curNode != null)
			_curNode.OnEnter();
		else
			UnityEngine.Debug.LogError($"Not found entry node : {entryNode}");
	}

	/// 
	/// 更新状态机
	/// 
	public static void Update()
	{
		if (_curNode != null)
			_curNode.OnUpdate();
	}

	/// 
	/// 加入一个节点
	/// 
	public static void AddNode(IFsmNode node)
	{
		if (node == null)
			throw new ArgumentNullException();

		if (_nodes.Contains(node) == false)
		{
			_nodes.Add(node);
		}
		else
		{
			UnityEngine.Debug.LogWarning($"Node {node.Name} already existed");
		}
	}

	/// 
	/// 转换节点
	/// 
	public static void Transition(string nodeName)
	{
		if (string.IsNullOrEmpty(nodeName))
			throw new ArgumentNullException();

		IFsmNode node = GetNode(nodeName);
		if (node == null)
		{
			UnityEngine.Debug.LogError($"Can not found node {nodeName}");
			return;
		}

		UnityEngine.Debug.Log($"FSM change {_curNode.Name} to {node.Name}");
		_preNode = _curNode;
		_curNode.OnExit();
		_curNode = node;
		_curNode.OnEnter();
	}

	/// 
	/// 返回到之前的节点
	/// 
	public static void RevertToPreviousNode()
	{
		Transition(PreviousNodeName);
	}

	private static bool IsContains(string nodeName)
	{
		for (int i = 0; i < _nodes.Count; i++)
		{
			if (_nodes[i].Name == nodeName)
				return true;
		}
		return false;
	}

	private static IFsmNode GetNode(string nodeName)
	{
		for (int i = 0; i < _nodes.Count; i++)
		{
			if (_nodes[i].Name == nodeName)
				return _nodes[i];
		}
		return null;
	}
}

你可能感兴趣的:(Unity实用技巧,源码学习,Unity,unity,学习,c#)