This commit is contained in:
2025-09-17 18:56:28 +08:00
commit 54c72710a5
5244 changed files with 5717609 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c1cc49e5bd383f040b0f9d481de62f04
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,4 @@
# UniFramework.Event
一个轻量级的事件系统。

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5dfad42c0d1a02f429a99108a35bbfce
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e86e06e6a95e6cc43940623bcc15721c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,48 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace UniFramework.Event
{
public class EventGroup
{
private readonly Dictionary<System.Type, List<Action<IEventMessage>>> _cachedListener = new Dictionary<System.Type, List<Action<IEventMessage>>>();
/// <summary>
/// 添加一个监听
/// </summary>
public void AddListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
{
System.Type eventType = typeof(TEvent);
if (_cachedListener.ContainsKey(eventType) == false)
_cachedListener.Add(eventType, new List<Action<IEventMessage>>());
if (_cachedListener[eventType].Contains(listener) == false)
{
_cachedListener[eventType].Add(listener);
UniEvent.AddListener(eventType, listener);
}
else
{
UniLogger.Warning($"Event listener is exist : {eventType}");
}
}
/// <summary>
/// 移除所有缓存的监听
/// </summary>
public void RemoveAllListener()
{
foreach (var pair in _cachedListener)
{
System.Type eventType = pair.Key;
for (int i = 0; i < pair.Value.Count; i++)
{
UniEvent.RemoveListener(eventType, pair.Value[i]);
}
pair.Value.Clear();
}
_cachedListener.Clear();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dcc5e4008d087434eb5db1390d8e4e6a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,7 @@

namespace UniFramework.Event
{
public interface IEventMessage
{
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7dcd12aabf986c6468f748911b1af65a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,206 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UniFramework.Event
{
public static class UniEvent
{
private class PostWrapper
{
public int PostFrame;
public int EventID;
public IEventMessage Message;
public void OnRelease()
{
PostFrame = 0;
EventID = 0;
Message = null;
}
}
private static bool _isInitialize = false;
private static GameObject _driver = null;
private static readonly Dictionary<int, LinkedList<Action<IEventMessage>>> _listeners = new Dictionary<int, LinkedList<Action<IEventMessage>>>(1000);
private static readonly List<PostWrapper> _postingList = new List<PostWrapper>(1000);
/// <summary>
/// 初始化事件系统
/// </summary>
public static void Initalize()
{
if (_isInitialize)
throw new Exception($"{nameof(UniEvent)} is initialized !");
if (_isInitialize == false)
{
// 创建驱动器
_isInitialize = true;
_driver = new UnityEngine.GameObject($"[{nameof(UniEvent)}]");
_driver.AddComponent<UniEventDriver>();
UnityEngine.Object.DontDestroyOnLoad(_driver);
UniLogger.Log($"{nameof(UniEvent)} initalize !");
}
}
/// <summary>
/// 销毁事件系统
/// </summary>
public static void Destroy()
{
if (_isInitialize)
{
ClearAll();
_isInitialize = false;
if (_driver != null)
GameObject.Destroy(_driver);
UniLogger.Log($"{nameof(UniEvent)} destroy all !");
}
}
/// <summary>
/// 更新事件系统
/// </summary>
internal static void Update()
{
for (int i = _postingList.Count - 1; i >= 0; i--)
{
var wrapper = _postingList[i];
if (UnityEngine.Time.frameCount > wrapper.PostFrame)
{
SendMessage(wrapper.EventID, wrapper.Message);
_postingList.RemoveAt(i);
}
}
}
/// <summary>
/// 清空所有监听
/// </summary>
public static void ClearAll()
{
foreach (int eventId in _listeners.Keys)
{
_listeners[eventId].Clear();
}
_listeners.Clear();
_postingList.Clear();
}
/// <summary>
/// 添加监听
/// </summary>
public static void AddListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
{
System.Type eventType = typeof(TEvent);
int eventId = eventType.GetHashCode();
AddListener(eventId, listener);
}
/// <summary>
/// 添加监听
/// </summary>
public static void AddListener(System.Type eventType, System.Action<IEventMessage> listener)
{
int eventId = eventType.GetHashCode();
AddListener(eventId, listener);
}
/// <summary>
/// 添加监听
/// </summary>
public static void AddListener(int eventId, System.Action<IEventMessage> listener)
{
if (_listeners.ContainsKey(eventId) == false)
_listeners.Add(eventId, new LinkedList<Action<IEventMessage>>());
if (_listeners[eventId].Contains(listener) == false)
_listeners[eventId].AddLast(listener);
}
/// <summary>
/// 移除监听
/// </summary>
public static void RemoveListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
{
System.Type eventType = typeof(TEvent);
int eventId = eventType.GetHashCode();
RemoveListener(eventId, listener);
}
/// <summary>
/// 移除监听
/// </summary>
public static void RemoveListener(System.Type eventType, System.Action<IEventMessage> listener)
{
int eventId = eventType.GetHashCode();
RemoveListener(eventId, listener);
}
/// <summary>
/// 移除监听
/// </summary>
public static void RemoveListener(int eventId, System.Action<IEventMessage> listener)
{
if (_listeners.ContainsKey(eventId))
{
if (_listeners[eventId].Contains(listener))
_listeners[eventId].Remove(listener);
}
}
/// <summary>
/// 实时广播事件
/// </summary>
public static void SendMessage(IEventMessage message)
{
int eventId = message.GetType().GetHashCode();
SendMessage(eventId, message);
}
/// <summary>
/// 实时广播事件
/// </summary>
public static void SendMessage(int eventId, IEventMessage message)
{
if (_listeners.ContainsKey(eventId) == false)
return;
LinkedList<Action<IEventMessage>> listeners = _listeners[eventId];
if (listeners.Count > 0)
{
var currentNode = listeners.Last;
while (currentNode != null)
{
currentNode.Value.Invoke(message);
currentNode = currentNode.Previous;
}
}
}
/// <summary>
/// 延迟广播事件
/// </summary>
public static void PostMessage(IEventMessage message)
{
int eventId = message.GetType().GetHashCode();
PostMessage(eventId, message);
}
/// <summary>
/// 延迟广播事件
/// </summary>
public static void PostMessage(int eventId, IEventMessage message)
{
var wrapper = new PostWrapper();
wrapper.PostFrame = UnityEngine.Time.frameCount;
wrapper.EventID = eventId;
wrapper.Message = message;
_postingList.Add(wrapper);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a2a39e0393e22c44b8416d1445c9bb2c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,12 @@
using UnityEngine;
namespace UniFramework.Event
{
internal class UniEventDriver : MonoBehaviour
{
void Update()
{
UniEvent.Update();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 91e57d06457f3ec40914e4d3ed58c070
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,16 @@
{
"name": "UniFramework.Event",
"rootNamespace": "",
"references": [
"GUID:e34a5702dd353724aa315fb8011f08c3"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f22fac247a56d2d41b687bb0d900e54e
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,21 @@
using System.Diagnostics;
namespace UniFramework.Event
{
internal static class UniLogger
{
[Conditional("DEBUG")]
public static void Log(string info)
{
UnityEngine.Debug.Log(info);
}
public static void Warning(string info)
{
UnityEngine.Debug.LogWarning(info);
}
public static void Error(string info)
{
UnityEngine.Debug.LogError(info);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9bb2f71f321705a4286de583f1c930d7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 72dcc846338391f44a4134c21f94723a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,3 @@
# UniFramework.Machine
一个轻量级的状态机。

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4c3656e4009078943b97b6dcca2c5063
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 26f3a6fd3a4f2a247a53a37334fd7624
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,11 @@

namespace UniFramework.Machine
{
public interface IStateNode
{
void OnCreate(StateMachine machine);
void OnEnter();
void OnUpdate();
void OnExit();
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 40fe73297598be84fb8dadedd4dd17e6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,172 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace UniFramework.Machine
{
public class StateMachine
{
private readonly Dictionary<string, System.Object> _blackboard = new Dictionary<string, object>(100);
private readonly Dictionary<string, IStateNode> _nodes = new Dictionary<string, IStateNode>(100);
private IStateNode _curNode;
private IStateNode _preNode;
/// <summary>
/// 状态机持有者
/// </summary>
public System.Object Owner { private set; get; }
/// <summary>
/// 当前运行的节点名称
/// </summary>
public string CurrentNode
{
get { return _curNode != null ? _curNode.GetType().FullName : string.Empty; }
}
/// <summary>
/// 之前运行的节点名称
/// </summary>
public string PreviousNode
{
get { return _preNode != null ? _preNode.GetType().FullName : string.Empty; }
}
private StateMachine() { }
public StateMachine(System.Object owner)
{
Owner = owner;
}
/// <summary>
/// 更新状态机
/// </summary>
public void Update()
{
if (_curNode != null)
_curNode.OnUpdate();
}
/// <summary>
/// 启动状态机
/// </summary>
public void Run<TNode>() where TNode : IStateNode
{
var nodeType = typeof(TNode);
var nodeName = nodeType.FullName;
Run(nodeName);
}
public void Run(Type entryNode)
{
var nodeName = entryNode.FullName;
Run(nodeName);
}
public void Run(string entryNode)
{
_curNode = TryGetNode(entryNode);
_preNode = _curNode;
if (_curNode == null)
throw new Exception($"Not found entry node: {entryNode }");
_curNode.OnEnter();
}
/// <summary>
/// 加入一个节点
/// </summary>
public void AddNode<TNode>() where TNode : IStateNode
{
var nodeType = typeof(TNode);
var stateNode = Activator.CreateInstance(nodeType) as IStateNode;
AddNode(stateNode);
}
public void AddNode(IStateNode stateNode)
{
if (stateNode == null)
throw new ArgumentNullException();
var nodeType = stateNode.GetType();
var nodeName = nodeType.FullName;
if (_nodes.ContainsKey(nodeName) == false)
{
stateNode.OnCreate(this);
_nodes.Add(nodeName, stateNode);
}
else
{
UniLogger.Error($"State node already existed : {nodeName}");
}
}
/// <summary>
/// 转换状态节点
/// </summary>
public void ChangeState<TNode>() where TNode : IStateNode
{
var nodeType = typeof(TNode);
var nodeName = nodeType.FullName;
ChangeState(nodeName);
}
public void ChangeState(Type nodeType)
{
var nodeName = nodeType.FullName;
ChangeState(nodeName);
}
public void ChangeState(string nodeName)
{
if (string.IsNullOrEmpty(nodeName))
throw new ArgumentNullException();
IStateNode node = TryGetNode(nodeName);
if (node == null)
{
UniLogger.Error($"Can not found state node : {nodeName}");
return;
}
UniLogger.Log($"{_curNode.GetType().FullName} --> {node.GetType().FullName}");
_preNode = _curNode;
_curNode.OnExit();
_curNode = node;
_curNode.OnEnter();
}
/// <summary>
/// 设置黑板数据
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void SetBlackboardValue(string key, System.Object value)
{
if (_blackboard.ContainsKey(key) == false)
_blackboard.Add(key, value);
else
_blackboard[key] = value;
}
/// <summary>
/// 获取黑板数据
/// </summary>
public System.Object GetBlackboardValue(string key)
{
if (_blackboard.TryGetValue(key, out System.Object value))
{
return value;
}
else
{
UniLogger.Warning($"Not found blackboard value : {key}");
return null;
}
}
private IStateNode TryGetNode(string nodeName)
{
_nodes.TryGetValue(nodeName, out IStateNode result);
return result;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bcbf86a86eb115a41b6aa61fb0945d43
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,16 @@
{
"name": "UniFramework.Machine",
"rootNamespace": "",
"references": [
"GUID:e34a5702dd353724aa315fb8011f08c3"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c55575a9f1747c240822f4b7e0400716
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,21 @@
using System.Diagnostics;
namespace UniFramework.Machine
{
internal static class UniLogger
{
[Conditional("DEBUG")]
public static void Log(string info)
{
UnityEngine.Debug.Log(info);
}
public static void Warning(string info)
{
UnityEngine.Debug.LogWarning(info);
}
public static void Error(string info)
{
UnityEngine.Debug.LogError(info);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: db25e4def3ffb6b468dd46b2a6fe1245
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 97c99cc0a7d8c8f42a1b15c81f6e71e0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,3 @@
# UniFramework.Utility
一些工具类。

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f055964b764f8cc41996f3c543307c85
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c3799338015524b47a601024fd574a90
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,69 @@
using System;
namespace UniFramework.Utility
{
internal struct BitMask32
{
private int _mask;
public static implicit operator int(BitMask32 mask) { return mask._mask; }
public static implicit operator BitMask32(int mask) { return new BitMask32(mask); }
public BitMask32(int mask)
{
_mask = mask;
}
/// <summary>
/// 打开位
/// </summary>
public void Open(int bit)
{
if (bit < 0 || bit > 31)
throw new ArgumentOutOfRangeException();
else
_mask |= 1 << bit;
}
/// <summary>
/// 关闭位
/// </summary>
public void Close(int bit)
{
if (bit < 0 || bit > 31)
throw new ArgumentOutOfRangeException();
else
_mask &= ~(1 << bit);
}
/// <summary>
/// 位取反
/// </summary>
public void Reverse(int bit)
{
if (bit < 0 || bit > 31)
throw new ArgumentOutOfRangeException();
else
_mask ^= 1 << bit;
}
/// <summary>
/// 所有位取反
/// </summary>
public void Inverse()
{
_mask = ~_mask;
}
/// <summary>
/// 比对位值
/// </summary>
public bool Test(int bit)
{
if (bit < 0 || bit > 31)
throw new ArgumentOutOfRangeException();
else
return (_mask & (1 << bit)) != 0;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 60c7594328ef976408edadfdf2b9aa3d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,69 @@
using System;
namespace UniFramework.Utility
{
internal struct BitMask64
{
private long _mask;
public static implicit operator long(BitMask64 mask) { return mask._mask; }
public static implicit operator BitMask64(long mask) { return new BitMask64(mask); }
public BitMask64(long mask)
{
_mask = mask;
}
/// <summary>
/// 打开位
/// </summary>
public void Open(int bit)
{
if (bit < 0 || bit > 63)
throw new ArgumentOutOfRangeException();
else
_mask |= 1L << bit;
}
/// <summary>
/// 关闭位
/// </summary>
public void Close(int bit)
{
if (bit < 0 || bit > 63)
throw new ArgumentOutOfRangeException();
else
_mask &= ~(1L << bit);
}
/// <summary>
/// 位取反
/// </summary>
public void Reverse(int bit)
{
if (bit < 0 || bit > 63)
throw new ArgumentOutOfRangeException();
else
_mask ^= 1L << bit;
}
/// <summary>
/// 所有位取反
/// </summary>
public void Inverse()
{
_mask = ~_mask;
}
/// <summary>
/// 比对位值
/// </summary>
public bool Test(int bit)
{
if (bit < 0 || bit > 63)
throw new ArgumentOutOfRangeException();
else
return (_mask & (1L << bit)) != 0;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6b03684bc5163694ab3983243512b4cc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,124 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace UniFramework.Utility
{
public static class StringConvert
{
/// <summary>
/// 正则表达式
/// </summary>
private static readonly Regex REGEX = new Regex(@"\{[-+]?[0-9]+\.?[0-9]*\}", RegexOptions.IgnoreCase);
/// <summary>
/// 字符串转换为BOOL
/// </summary>
public static bool StringToBool(string str)
{
int value = (int)Convert.ChangeType(str, typeof(int));
return value > 0;
}
/// <summary>
/// 字符串转换为数值
/// </summary>
public static T StringToValue<T>(string str)
{
return (T)Convert.ChangeType(str, typeof(T));
}
/// <summary>
/// 字符串转换为数值列表
/// </summary>
/// <param name="separator">分隔符</param>
public static List<T> StringToValueList<T>(string str, char separator)
{
List<T> result = new List<T>();
if (!String.IsNullOrEmpty(str))
{
string[] splits = str.Split(separator);
foreach (string split in splits)
{
if (!String.IsNullOrEmpty(split))
{
result.Add((T)Convert.ChangeType(split, typeof(T)));
}
}
}
return result;
}
/// <summary>
/// 字符串转为字符串列表
/// </summary>
public static List<string> StringToStringList(string str, char separator)
{
List<string> result = new List<string>();
if (!String.IsNullOrEmpty(str))
{
string[] splits = str.Split(separator);
foreach (string split in splits)
{
if (!String.IsNullOrEmpty(split))
{
result.Add(split);
}
}
}
return result;
}
/// <summary>
/// 转换为枚举
/// 枚举索引转换为枚举类型
/// </summary>
public static T IndexToEnum<T>(string index) where T : IConvertible
{
int enumIndex = (int)Convert.ChangeType(index, typeof(int));
return IndexToEnum<T>(enumIndex);
}
/// <summary>
/// 转换为枚举
/// 枚举索引转换为枚举类型
/// </summary>
public static T IndexToEnum<T>(int index) where T : IConvertible
{
if (Enum.IsDefined(typeof(T), index) == false)
{
throw new ArgumentException($"Enum {typeof(T)} is not defined index {index}");
}
return (T)Enum.ToObject(typeof(T), index);
}
/// <summary>
/// 转换为枚举
/// 枚举名称转换为枚举类型
/// </summary>
public static T NameToEnum<T>(string name)
{
if (Enum.IsDefined(typeof(T), name) == false)
{
throw new ArgumentException($"Enum {typeof(T)} is not defined name {name}");
}
return (T)Enum.Parse(typeof(T), name);
}
/// <summary>
/// 字符串转换为参数列表
/// </summary>
public static List<float> StringToParams(string str)
{
List<float> result = new List<float>();
MatchCollection matches = REGEX.Matches(str);
for (int i = 0; i < matches.Count; i++)
{
string value = matches[i].Value.Trim('{', '}');
result.Add(StringToValue<float>(value));
}
return result;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 889d01b55e38f7c49bbfb8908d9bf17f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,51 @@
using System;
using System.Text;
namespace UniFramework.Utility
{
public static class StringFormat
{
[ThreadStatic]
private static StringBuilder _cacheBuilder = new StringBuilder(1024);
public static string Format(string format, object arg0)
{
if (string.IsNullOrEmpty(format))
throw new ArgumentNullException();
_cacheBuilder.Length = 0;
_cacheBuilder.AppendFormat(format, arg0);
return _cacheBuilder.ToString();
}
public static string Format(string format, object arg0, object arg1)
{
if (string.IsNullOrEmpty(format))
throw new ArgumentNullException();
_cacheBuilder.Length = 0;
_cacheBuilder.AppendFormat(format, arg0, arg1);
return _cacheBuilder.ToString();
}
public static string Format(string format, object arg0, object arg1, object arg2)
{
if (string.IsNullOrEmpty(format))
throw new ArgumentNullException();
_cacheBuilder.Length = 0;
_cacheBuilder.AppendFormat(format, arg0, arg1, arg2);
return _cacheBuilder.ToString();
}
public static string Format(string format, params object[] args)
{
if (string.IsNullOrEmpty(format))
throw new ArgumentNullException();
if (args == null)
throw new ArgumentNullException();
_cacheBuilder.Length = 0;
_cacheBuilder.AppendFormat(format, args);
return _cacheBuilder.ToString();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 86ae09fcbdc5301499fb61e9bd4a5794
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,14 @@
{
"name": "UniFramework.Utility",
"rootNamespace": "",
"references": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1ea6b676786131e4095182b742bb64ec
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,199 @@

namespace UniFramework.Utility
{
public sealed class UniTimer
{
/// <summary>
/// 延迟后,触发一次
/// </summary>
public static UniTimer CreateOnceTimer(float delay)
{
return new UniTimer(delay, -1, -1, 1);
}
/// <summary>
/// 延迟后,永久性的间隔触发
/// </summary>
/// <param name="delay">延迟时间</param>
/// <param name="interval">间隔时间</param>
public static UniTimer CreatePepeatTimer(float delay, float interval)
{
return new UniTimer(delay, interval, -1, -1);
}
/// <summary>
/// 延迟后,在一段时间内间隔触发
/// </summary>
/// <param name="delay">延迟时间</param>
/// <param name="interval">间隔时间</param>
/// <param name="duration">触发周期</param>
public static UniTimer CreatePepeatTimer(float delay, float interval, float duration)
{
return new UniTimer(delay, interval, duration, -1);
}
/// <summary>
/// 延迟后,间隔触发一定次数
/// </summary>
/// <param name="delay">延迟时间</param>
/// <param name="interval">间隔时间</param>
/// <param name="maxTriggerCount">最大触发次数</param>
public static UniTimer CreatePepeatTimer(float delay, float interval, long maxTriggerCount)
{
return new UniTimer(delay, interval, -1, maxTriggerCount);
}
/// <summary>
/// 延迟后,在一段时间内触发
/// </summary>
/// <param name="delay">延迟时间</param>
/// <param name="duration">触发周期</param>
public static UniTimer CreateDurationTimer(float delay, float duration)
{
return new UniTimer(delay, -1, duration, -1);
}
/// <summary>
/// 延迟后,永久触发
/// </summary>
public static UniTimer CreateForeverTimer(float delay)
{
return new UniTimer(delay, -1, -1, -1);
}
private readonly float _intervalTime;
private readonly float _durationTime;
private readonly long _maxTriggerCount;
// 需要重置的变量
private float _delayTimer = 0;
private float _durationTimer = 0;
private float _intervalTimer = 0;
private long _triggerCount = 0;
/// <summary>
/// 延迟时间
/// </summary>
public float DelayTime { private set; get; }
/// <summary>
/// 是否已经结束
/// </summary>
public bool IsOver { private set; get; }
/// <summary>
/// 是否已经暂停
/// </summary>
public bool IsPause { private set; get; }
/// <summary>
/// 延迟剩余时间
/// </summary>
public float Remaining
{
get
{
if (IsOver)
return 0f;
else
return System.Math.Max(0f, DelayTime - _delayTimer);
}
}
/// <summary>
/// 计时器
/// </summary>
/// <param name="delay">延迟时间</param>
/// <param name="interval">间隔时间</param>
/// <param name="duration">运行时间</param>
/// <param name="maxTriggerTimes">最大触发次数</param>
public UniTimer(float delay, float interval, float duration, long maxTriggerCount)
{
DelayTime = delay;
_intervalTime = interval;
_durationTime = duration;
_maxTriggerCount = maxTriggerCount;
}
/// <summary>
/// 暂停计时器
/// </summary>
public void Pause()
{
IsPause = true;
}
/// <summary>
/// 恢复计时器
/// </summary>
public void Resume()
{
IsPause = false;
}
/// <summary>
/// 结束计时器
/// </summary>
public void Kill()
{
IsOver = true;
}
/// <summary>
/// 重置计时器
/// </summary>
public void Reset()
{
_delayTimer = 0;
_durationTimer = 0;
_intervalTimer = 0;
_triggerCount = 0;
IsOver = false;
IsPause = false;
}
/// <summary>
/// 更新计时器
/// </summary>
public bool Update(float deltaTime)
{
if (IsOver || IsPause)
return false;
_delayTimer += deltaTime;
if (_delayTimer < DelayTime)
return false;
if(_intervalTime > 0)
_intervalTimer += deltaTime;
if (_durationTime > 0)
_durationTimer += deltaTime;
// 检测间隔执行
if (_intervalTime > 0)
{
if (_intervalTimer < _intervalTime)
return false;
_intervalTimer = 0;
}
// 检测结束条件
if (_durationTime > 0)
{
if (_durationTimer >= _durationTime)
Kill();
}
// 检测结束条件
if (_maxTriggerCount > 0)
{
_triggerCount++;
if (_triggerCount >= _maxTriggerCount)
Kill();
}
return true;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a9ba1e57e76e1c3498c1e678e2737ab2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: