update sample

This commit is contained in:
hevinci
2022-11-25 21:40:54 +08:00
parent 82cff36194
commit 5718d57b88
223 changed files with 5950 additions and 2216 deletions
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f2801816f5bf9e74eb7f2e2b340ad4cc
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,4 @@
# UniFramework.Event
一个轻量级的事件系统。
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5dfad42c0d1a02f429a99108a35bbfce
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e86e06e6a95e6cc43940623bcc15721c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -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();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dcc5e4008d087434eb5db1390d8e4e6a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
namespace UniFramework.Event
{
public interface IEventMessage
{
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7dcd12aabf986c6468f748911b1af65a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
{
"name": "UniEvent",
"rootNamespace": "",
"references": [
"GUID:e34a5702dd353724aa315fb8011f08c3"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f22fac247a56d2d41b687bb0d900e54e
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,203 @@
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 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;
GameObject driver = new UnityEngine.GameObject($"[{nameof(UniEvent)}]");
driver.AddComponent<UniEventDriver>();
UnityEngine.Object.DontDestroyOnLoad(driver);
}
}
/// <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>
internal static void Destroy()
{
if (_isInitialize)
{
_isInitialize = false;
ClearAll();
UniLogger.Log($"{nameof(UniEvent)} destroy all !");
}
}
/// <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);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a2a39e0393e22c44b8416d1445c9bb2c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
using UnityEngine;
namespace UniFramework.Event
{
internal class UniEventDriver : MonoBehaviour
{
void Update()
{
UniEvent.Update();
}
void OnDestroy()
{
UniEvent.Destroy();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 91e57d06457f3ec40914e4d3ed58c070
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -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);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9bb2f71f321705a4286de583f1c930d7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 16d76e3e6337b0c4cae28696d4be4c7c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
# UniFramework.Event
一个轻量级的状态机。
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4c3656e4009078943b97b6dcca2c5063
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 26f3a6fd3a4f2a247a53a37334fd7624
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
namespace UniFramework.Machine
{
public interface IStateNode
{
void OnCreate(StateMachine machine);
void OnEnter();
void OnUpdate();
void OnExit();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 19d466eecc32f6a478d64f6a78748b23
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,142 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace UniFramework.Machine
{
public class StateMachine
{
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();
}
private IStateNode TryGetNode(string nodeName)
{
_nodes.TryGetValue(nodeName, out IStateNode result);
return result;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5999045dd15678e4bbaca21f460ea0e6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -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);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: db25e4def3ffb6b468dd46b2a6fe1245
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
{
"name": "UniMachine",
"rootNamespace": "",
"references": [
"GUID:e34a5702dd353724aa315fb8011f08c3"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c55575a9f1747c240822f4b7e0400716
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4e57ebf0b48a9d94dba1c0ce723da392
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
# UniFramework.Module
一个轻量级的模块系统。
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 496f400bdfe0c6c46809be47d2a45b37
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: aef3e45fdde94b245841e6e62655912f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,21 @@
namespace UniFramework.Module
{
public interface IModule
{
/// <summary>
/// 创建模块
/// </summary>
void OnCreate(System.Object createParam);
/// <summary>
/// 更新模块
/// </summary>
void OnUpdate();
/// <summary>
/// 销毁模块
/// </summary>
void OnDestroy();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4f4757101f8553d49ad6da27c94c50c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,28 @@
namespace UniFramework.Module
{
public abstract class ModuleSingleton<T> where T : class, IModule
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
UniLogger.Error($"{typeof(T)} is not create. Use {nameof(UniModule)}.{nameof(UniModule.CreateModule)} create.");
return _instance;
}
}
protected ModuleSingleton()
{
if (_instance != null)
throw new System.Exception($"{typeof(T)} instance already created.");
_instance = this as T;
}
protected void DestroySingleton()
{
_instance = null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b6c8230c0d097534e950f4e84ce01e96
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,21 @@
using System.Diagnostics;
namespace UniFramework.Module
{
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);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b2a99934c26e0304cb6292b0c40ae684
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
{
"name": "UniModule",
"rootNamespace": "",
"references": [
"GUID:e34a5702dd353724aa315fb8011f08c3"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: b35e33884f6755d43b7e0511e88956d0
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,222 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UniFramework.Module
{
public static class UniModule
{
private class Wrapper
{
public int Priority { private set; get; }
public IModule Module { private set; get; }
public Wrapper(IModule module, int priority)
{
Module = module;
Priority = priority;
}
}
private static bool _isInitialize = false;
private static readonly List<Wrapper> _wrappers = new List<Wrapper>(100);
private static MonoBehaviour _behaviour;
private static bool _isDirty = false;
/// <summary>
/// 初始化模块系统
/// </summary>
public static void Initialize()
{
if (_isInitialize)
throw new Exception($"{nameof(UniModule)} is initialized !");
if (_isInitialize == false)
{
// 创建驱动器
_isInitialize = true;
GameObject driver = new UnityEngine.GameObject($"[{nameof(UniModule)}]");
_behaviour = driver.AddComponent<UniModuleDriver>();
UnityEngine.Object.DontDestroyOnLoad(driver);
}
}
/// <summary>
/// 更新模块系统
/// </summary>
internal static void Update()
{
// 如果需要重新排序
if (_isDirty)
{
_isDirty = false;
_wrappers.Sort((left, right) =>
{
if (left.Priority > right.Priority)
return -1;
else if (left.Priority == right.Priority)
return 0;
else
return 1;
});
}
// 轮询所有模块
for (int i = 0; i < _wrappers.Count; i++)
{
_wrappers[i].Module.OnUpdate();
}
}
/// <summary>
/// 销毁模块系统
/// </summary>
internal static void Destroy()
{
if (_isInitialize)
{
_isInitialize = false;
DestroyAll();
UniLogger.Log($"{nameof(UniModule)} destroy all !");
}
}
/// <summary>
/// 获取模块
/// </summary>
public static T GetModule<T>() where T : class, IModule
{
System.Type type = typeof(T);
for (int i = 0; i < _wrappers.Count; i++)
{
if (_wrappers[i].Module.GetType() == type)
return _wrappers[i].Module as T;
}
UniLogger.Error($"Not found manager : {type}");
return null;
}
/// <summary>
/// 查询模块是否存在
/// </summary>
public static bool Contains<T>() where T : class, IModule
{
System.Type type = typeof(T);
for (int i = 0; i < _wrappers.Count; i++)
{
if (_wrappers[i].Module.GetType() == type)
return true;
}
return false;
}
/// <summary>
/// 创建模块
/// </summary>
/// <param name="priority">运行时的优先级,优先级越大越早执行。如果没有设置优先级,那么会按照添加顺序执行</param>
public static T CreateModule<T>(int priority = 0) where T : class, IModule
{
return CreateModule<T>(null, priority);
}
/// <summary>
/// 创建模块
/// </summary>
/// <param name="createParam">附加参数</param>
/// <param name="priority">运行时的优先级,优先级越大越早执行。如果没有设置优先级,那么会按照添加顺序执行</param>
public static T CreateModule<T>(System.Object createParam, int priority = 0) where T : class, IModule
{
if (priority < 0)
throw new Exception("The priority can not be negative");
if (Contains<T>())
throw new Exception($"Module is already existed : {typeof(T)}");
// 如果没有设置优先级
if (priority == 0)
{
int minPriority = GetMinPriority();
priority = --minPriority;
}
T module = Activator.CreateInstance<T>();
Wrapper wrapper = new Wrapper(module, priority);
wrapper.Module.OnCreate(createParam);
_wrappers.Add(wrapper);
_isDirty = true;
return module;
}
/// <summary>
/// 销毁模块
/// </summary>
public static bool DestroyModule<T>() where T : class, IModule
{
var type = typeof(T);
for (int i = 0; i < _wrappers.Count; i++)
{
if (_wrappers[i].Module.GetType() == type)
{
_wrappers[i].Module.OnDestroy();
_wrappers.RemoveAt(i);
return true;
}
}
return false;
}
/// <summary>
/// 开启一个协程
/// </summary>
public static Coroutine StartCoroutine(IEnumerator coroutine)
{
return _behaviour.StartCoroutine(coroutine);
}
public static Coroutine StartCoroutine(string methodName)
{
return _behaviour.StartCoroutine(methodName);
}
/// <summary>
/// 停止一个协程
/// </summary>
public static void StopCoroutine(Coroutine coroutine)
{
_behaviour.StopCoroutine(coroutine);
}
public static void StopCoroutine(string methodName)
{
_behaviour.StopCoroutine(methodName);
}
/// <summary>
/// 停止所有协程
/// </summary>
public static void StopAllCoroutines()
{
_behaviour.StopAllCoroutines();
}
private static int GetMinPriority()
{
int minPriority = 0;
for (int i = 0; i < _wrappers.Count; i++)
{
if (_wrappers[i].Priority < minPriority)
minPriority = _wrappers[i].Priority;
}
return minPriority; //小于等于零
}
private static void DestroyAll()
{
for (int i = 0; i < _wrappers.Count; i++)
{
_wrappers[i].Module.OnDestroy();
}
_wrappers.Clear();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b799b83d73a9cb543b2504ccb1cf796a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
using UnityEngine;
namespace UniFramework.Module
{
internal class UniModuleDriver : MonoBehaviour
{
void Update()
{
UniModule.Update();
}
void OnDestroy()
{
UniModule.Destroy();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f0b2648cd533049449e1e81d215afbd7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7cfeaa68459d1cb4f96e62f6b7bd9fd7
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,36 @@
# UniFramework.Pooling
一个功能强大的游戏对象池系统。
该系统依赖于YooAsset资源系统,支持各类异步编程,支持同步接口和异步接口。
```c#
using UnityEngine;
using YooAsset;
using UniFramework.Pooling;
IEnumerator Start()
{
// 初始化游戏对象池系统
UniPooling.Initalize();
// 创建孵化器
var spawner = UniPooling.CreateSpawner("DefaultPackage");
// 创建Cube预制体的对象池
var operation = spawner.CreateGameObjectPoolAsync("Cube.prefab");
yield return operation;
// 孵化Cube游戏对象
SpawnHandle handle = spawner.SpawnAsync("Cube.prefab");
yield return handle;
Debug.Log(handle.GameObj.name);
// 回收游戏对象
handle.Restore();
// 丢弃游戏对象
handle.Discard();
}
```
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7976cbcaa4dcfcc4b932fb01d6c0499a
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5904699460a22064182a5cf9129fc09e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,70 @@
using YooAsset;
namespace UniFramework.Pooling
{
public class CreatePoolOperation : GameAsyncOperation
{
private enum ESteps
{
None,
Waiting,
Done,
}
private readonly AssetOperationHandle _handle;
private ESteps _steps = ESteps.None;
internal CreatePoolOperation(AssetOperationHandle handle)
{
_handle = handle;
}
protected override void OnStart()
{
_steps = ESteps.Waiting;
}
protected override void OnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.Waiting)
{
if (_handle.IsValid == false)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{nameof(AssetOperationHandle)} is invalid.";
return;
}
if (_handle.IsDone == false)
return;
if (_handle.AssetObject == null)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{nameof(AssetOperationHandle.AssetObject)} is null.";
return;
}
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
/// <summary>
/// 等待异步实例化结束
/// </summary>
public void WaitForAsyncComplete()
{
if (_handle != null)
{
if (_steps == ESteps.Done)
return;
_handle.WaitForAsyncComplete();
OnUpdate();
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a5687620a17f42e4085a0e2243be7561
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,215 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
namespace UniFramework.Pooling
{
internal class GameObjectPool
{
private readonly Transform _poolRoot;
private readonly Queue<InstantiateOperation> _cacheOperations;
private readonly bool _dontDestroy;
private readonly int _initCapacity;
private readonly int _maxCapacity;
private readonly float _destroyTime;
private float _lastRestoreRealTime = -1f;
/// <summary>
/// 资源句柄
/// </summary>
public AssetOperationHandle AssetHandle { private set; get; }
/// <summary>
/// 资源定位地址
/// </summary>
public string Location { private set; get; }
/// <summary>
/// 内部缓存总数
/// </summary>
public int CacheCount
{
get { return _cacheOperations.Count; }
}
/// <summary>
/// 外部使用总数
/// </summary>
public int SpawnCount { private set; get; } = 0;
/// <summary>
/// 是否常驻不销毁
/// </summary>
public bool DontDestroy
{
get { return _dontDestroy; }
}
public GameObjectPool(GameObject poolRoot, string location, bool dontDestroy, int initCapacity, int maxCapacity, float destroyTime)
{
_poolRoot = poolRoot.transform;
Location = location;
_dontDestroy = dontDestroy;
_initCapacity = initCapacity;
_maxCapacity = maxCapacity;
_destroyTime = destroyTime;
// 创建缓存池
_cacheOperations = new Queue<InstantiateOperation>(initCapacity);
}
/// <summary>
/// 创建对象池
/// </summary>
public void CreatePool(AssetsPackage assetPackage)
{
// 加载游戏对象
AssetHandle = assetPackage.LoadAssetAsync<GameObject>(Location);
// 创建初始对象
for (int i = 0; i < _initCapacity; i++)
{
var operation = AssetHandle.InstantiateAsync(_poolRoot);
_cacheOperations.Enqueue(operation);
}
}
/// <summary>
/// 销毁游戏对象池
/// </summary>
public void DestroyPool()
{
// 卸载资源对象
AssetHandle.Release();
AssetHandle = null;
// 销毁游戏对象
foreach (var operation in _cacheOperations)
{
if (operation.Result != null)
GameObject.Destroy(operation.Result);
}
_cacheOperations.Clear();
SpawnCount = 0;
}
/// <summary>
/// 查询静默时间内是否可以销毁
/// </summary>
public bool CanAutoDestroy()
{
if (_dontDestroy)
return false;
if (_destroyTime < 0)
return false;
if (_lastRestoreRealTime > 0 && SpawnCount <= 0)
return (Time.realtimeSinceStartup - _lastRestoreRealTime) > _destroyTime;
else
return false;
}
/// <summary>
/// 游戏对象池是否已经销毁
/// </summary>
public bool IsDestroyed()
{
return AssetHandle == null;
}
/// <summary>
/// 回收
/// </summary>
public void Restore(InstantiateOperation operation)
{
if (IsDestroyed())
{
DestroyInstantiateOperation(operation);
return;
}
SpawnCount--;
if (SpawnCount <= 0)
_lastRestoreRealTime = Time.realtimeSinceStartup;
// 如果外部逻辑销毁了游戏对象
if (operation.Status == EOperationStatus.Succeed)
{
if (operation.Result == null)
return;
}
// 如果缓存池还未满员
if (_cacheOperations.Count < _maxCapacity)
{
SetRestoreGameObject(operation.Result);
_cacheOperations.Enqueue(operation);
}
else
{
DestroyInstantiateOperation(operation);
}
}
/// <summary>
/// 丢弃
/// </summary>
public void Discard(InstantiateOperation operation)
{
if (IsDestroyed())
{
DestroyInstantiateOperation(operation);
return;
}
SpawnCount--;
if (SpawnCount <= 0)
_lastRestoreRealTime = Time.realtimeSinceStartup;
DestroyInstantiateOperation(operation);
}
/// <summary>
/// 获取一个游戏对象
/// </summary>
public SpawnHandle Spawn(Transform parent, Vector3 position, Quaternion rotation, bool forceClone, params System.Object[] userDatas)
{
InstantiateOperation operation;
if (forceClone == false && _cacheOperations.Count > 0)
operation = _cacheOperations.Dequeue();
else
operation = AssetHandle.InstantiateAsync();
SpawnCount++;
SpawnHandle handle = new SpawnHandle(this, operation, parent, position, rotation, userDatas);
YooAssets.StartOperation(handle);
return handle;
}
private void DestroyInstantiateOperation(InstantiateOperation operation)
{
// 取消异步操作
operation.Cancel();
// 销毁游戏对象
if (operation.Result != null)
{
GameObject.Destroy(operation.Result);
}
}
private void SetRestoreGameObject(GameObject gameObj)
{
if (gameObj != null)
{
gameObj.SetActive(false);
gameObj.transform.SetParent(_poolRoot);
gameObj.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1dd976626eb4ca645b4ec80921f4e8fd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,148 @@
using UnityEngine;
using YooAsset;
namespace UniFramework.Pooling
{
public sealed class SpawnHandle : GameAsyncOperation
{
private enum ESteps
{
None,
Waiting,
Done,
}
private readonly GameObjectPool _pool;
private InstantiateOperation _operation;
private readonly Transform _parent;
private readonly Vector3 _position;
private readonly Quaternion _rotation;
private ESteps _steps = ESteps.None;
/// <summary>
/// 实例化的游戏对象
/// </summary>
public GameObject GameObj
{
get
{
if (_operation == null)
{
UniLogger.Warning("The spawn handle is invalid !");
return null;
}
return _operation.Result;
}
}
/// <summary>
/// 用户自定义数据集
/// </summary>
public System.Object[] UserDatas { private set; get; }
private SpawnHandle()
{
}
internal SpawnHandle(GameObjectPool pool, InstantiateOperation operation, Transform parent, Vector3 position, Quaternion rotation, params System.Object[] userDatas)
{
_pool = pool;
_operation = operation;
_parent = parent;
_position = position;
_rotation = rotation;
UserDatas = userDatas;
}
protected override void OnStart()
{
_steps = ESteps.Waiting;
}
protected override void OnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.Waiting)
{
if (_operation.IsDone == false)
return;
if (_operation.Status != EOperationStatus.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _operation.Error;
return;
}
if (_operation.Result == null)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Clone game object is null.";
return;
}
// 设置参数
_operation.Result.transform.SetParent(_parent);
_operation.Result.transform.SetPositionAndRotation(_position, _rotation);
_operation.Result.SetActive(true);
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
/// <summary>
/// 回收
/// </summary>
public void Restore()
{
if (_operation != null)
{
ClearCompletedCallback();
CancelHandle();
_pool.Restore(_operation);
_operation = null;
}
}
/// <summary>
/// 丢弃
/// </summary>
public void Discard()
{
if (_operation != null)
{
ClearCompletedCallback();
CancelHandle();
_pool.Discard(_operation);
_operation = null;
}
}
/// <summary>
/// 等待异步实例化结束
/// </summary>
public void WaitForAsyncComplete()
{
if (_operation != null)
{
if (_steps == ESteps.Done)
return;
_operation.WaitForAsyncComplete();
OnUpdate();
}
}
private void CancelHandle()
{
if (IsDone == false)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"User cancelled !";
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6350d2984a149b349b9cec658d21b12a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,259 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
namespace UniFramework.Pooling
{
public class Spawner
{
private readonly List<GameObjectPool> _gameObjectPools = new List<GameObjectPool>(100);
private readonly List<GameObjectPool> _removeList = new List<GameObjectPool>(100);
private readonly GameObject _spawnerRoot;
private readonly AssetsPackage _assetPackage;
public string PackageName
{
get
{
return _assetPackage.PackageName;
}
}
private Spawner()
{
}
internal Spawner(GameObject poolingRoot, AssetsPackage assetPackage)
{
_spawnerRoot = new GameObject($"{assetPackage.PackageName}");
_spawnerRoot.transform.SetParent(poolingRoot.transform);
_assetPackage = assetPackage;
}
/// <summary>
/// 更新游戏对象池系统
/// </summary>
internal void Update()
{
_removeList.Clear();
foreach (var pool in _gameObjectPools)
{
if (pool.CanAutoDestroy())
_removeList.Add(pool);
}
foreach (var pool in _removeList)
{
_gameObjectPools.Remove(pool);
pool.DestroyPool();
}
}
/// <summary>
/// 销毁游戏对象池系统
/// </summary>
internal void Destroy()
{
DestroyAll(true);
}
/// <summary>
/// 销毁所有对象池及其资源
/// </summary>
/// <param name="includeAll">销毁所有对象池,包括常驻对象池</param>
public void DestroyAll(bool includeAll)
{
if (includeAll)
{
foreach (var pool in _gameObjectPools)
{
pool.DestroyPool();
}
_gameObjectPools.Clear();
}
else
{
List<GameObjectPool> removeList = new List<GameObjectPool>();
foreach (var pool in _gameObjectPools)
{
if (pool.DontDestroy == false)
removeList.Add(pool);
}
foreach (var pool in removeList)
{
_gameObjectPools.Remove(pool);
pool.DestroyPool();
}
}
}
/// <summary>
/// 异步创建指定资源的游戏对象池
/// </summary>
/// <param name="location">资源定位地址</param>
/// <param name="dontDestroy">资源常驻不销毁</param>
/// <param name="initCapacity">对象池的初始容量</param>
/// <param name="maxCapacity">对象池的最大容量</param>
/// <param name="destroyTime">静默销毁时间(注意:小于零代表不主动销毁)</param>
public CreatePoolOperation CreateGameObjectPoolAsync(string location, bool dontDestroy = false, int initCapacity = 0, int maxCapacity = int.MaxValue, float destroyTime = -1f)
{
return CreateGameObjectPoolInternal(location, dontDestroy, initCapacity, maxCapacity, destroyTime);
}
/// <summary>
/// 同步创建指定资源的游戏对象池
/// </summary>
/// <param name="location">资源定位地址</param>
/// <param name="dontDestroy">资源常驻不销毁</param>
/// <param name="initCapacity">对象池的初始容量</param>
/// <param name="maxCapacity">对象池的最大容量</param>
/// <param name="destroyTime">静默销毁时间(注意:小于零代表不主动销毁)</param>
public CreatePoolOperation CreateGameObjectPoolSync(string location, bool dontDestroy = false, int initCapacity = 0, int maxCapacity = int.MaxValue, float destroyTime = -1f)
{
var operation = CreateGameObjectPoolInternal(location, dontDestroy, initCapacity, maxCapacity, destroyTime);
operation.WaitForAsyncComplete();
return operation;
}
/// <summary>
/// 创建指定资源的游戏对象池
/// </summary>
private CreatePoolOperation CreateGameObjectPoolInternal(string location, bool dontDestroy = false, int initCapacity = 0, int maxCapacity = int.MaxValue, float destroyTime = -1f)
{
if (maxCapacity < initCapacity)
throw new Exception("The max capacity value must be greater the init capacity value.");
GameObjectPool pool = TryGetGameObjectPool(location);
if (pool != null)
{
UniLogger.Warning($"GameObject pool is already existed : {location}");
var operation = new CreatePoolOperation(pool.AssetHandle);
YooAssets.StartOperation(operation);
return operation;
}
else
{
pool = new GameObjectPool(_spawnerRoot, location, dontDestroy, initCapacity, maxCapacity, destroyTime);
pool.CreatePool(_assetPackage);
_gameObjectPools.Add(pool);
var operation = new CreatePoolOperation(pool.AssetHandle);
YooAssets.StartOperation(operation);
return operation;
}
}
/// <summary>
/// 异步实例化一个游戏对象
/// </summary>
/// <param name="location">资源定位地址</param>
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
/// <param name="userDatas">用户自定义数据</param>
public SpawnHandle SpawnAsync(string location, bool forceClone = false, params System.Object[] userDatas)
{
return SpawnInternal(location, null, Vector3.zero, Quaternion.identity, forceClone, userDatas);
}
/// <summary>
/// 异步实例化一个游戏对象
/// </summary>
/// <param name="location">资源定位地址</param>
/// <param name="parent">父物体</param>
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
/// <param name="userDatas">用户自定义数据</param>
public SpawnHandle SpawnAsync(string location, Transform parent, bool forceClone = false, params System.Object[] userDatas)
{
return SpawnInternal(location, parent, Vector3.zero, Quaternion.identity, forceClone, userDatas);
}
/// <summary>
/// 异步实例化一个游戏对象
/// </summary>
/// <param name="location">资源定位地址</param>
/// <param name="parent">父物体</param>
/// <param name="position">世界坐标</param>
/// <param name="rotation">世界角度</param>
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
/// <param name="userDatas">用户自定义数据</param>
public SpawnHandle SpawnAsync(string location, Transform parent, Vector3 position, Quaternion rotation, bool forceClone = false, params System.Object[] userDatas)
{
return SpawnInternal(location, parent, position, rotation, forceClone, userDatas);
}
/// <summary>
/// 同步实例化一个游戏对象
/// </summary>
/// <param name="location">资源定位地址</param>
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
/// <param name="userDatas">用户自定义数据</param>
public SpawnHandle SpawnSync(string location, bool forceClone = false, params System.Object[] userDatas)
{
SpawnHandle handle = SpawnInternal(location, null, Vector3.zero, Quaternion.identity, forceClone, userDatas);
handle.WaitForAsyncComplete();
return handle;
}
/// <summary>
/// 同步实例化一个游戏对象
/// </summary>
/// <param name="location">资源定位地址</param>
/// <param name="parent">父物体</param>
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
/// <param name="userDatas">用户自定义数据</param>
public SpawnHandle SpawnSync(string location, Transform parent, bool forceClone = false, params System.Object[] userDatas)
{
SpawnHandle handle = SpawnInternal(location, parent, Vector3.zero, Quaternion.identity, forceClone, userDatas);
handle.WaitForAsyncComplete();
return handle;
}
/// <summary>
/// 同步实例化一个游戏对象
/// </summary>
/// <param name="location">资源定位地址</param>
/// <param name="parent">父物体</param>
/// <param name="position">世界坐标</param>
/// <param name="rotation">世界角度</param>
/// <param name="forceClone">强制克隆游戏对象,忽略缓存池里的对象</param>
/// <param name="userDatas">用户自定义数据</param>
public SpawnHandle SpawnSync(string location, Transform parent, Vector3 position, Quaternion rotation, bool forceClone = false, params System.Object[] userDatas)
{
SpawnHandle handle = SpawnInternal(location, parent, position, rotation, forceClone, userDatas);
handle.WaitForAsyncComplete();
return handle;
}
/// <summary>
/// 实例化一个游戏对象
/// </summary>
private SpawnHandle SpawnInternal(string location, Transform parent, Vector3 position, Quaternion rotation, bool forceClone, params System.Object[] userDatas)
{
var pool = TryGetGameObjectPool(location);
if (pool != null)
{
return pool.Spawn(parent, position, rotation, forceClone, userDatas);
}
// 如果不存在创建游戏对象池
pool = new GameObjectPool(_spawnerRoot, location, false, 0, int.MaxValue, -1f);
pool.CreatePool(_assetPackage);
_gameObjectPools.Add(pool);
return pool.Spawn(parent, position, rotation, forceClone, userDatas);
}
private GameObjectPool TryGetGameObjectPool(string location)
{
foreach (var pool in _gameObjectPools)
{
if (pool.Location == location)
return pool;
}
return null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6c0b7912d44674d47a5b7240670dcc87
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,21 @@
using System.Diagnostics;
namespace UniFramework.Pooling
{
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);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 50142a5596fb6c1439dced35faef4d4c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
{
"name": "UniPooling",
"rootNamespace": "",
"references": [
"GUID:e34a5702dd353724aa315fb8011f08c3"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: b0a84d582f6a6fa4185f67ce934d99c2
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,125 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
namespace UniFramework.Pooling
{
/// <summary>
/// 游戏对象池系统
/// </summary>
public static class UniPooling
{
private static bool _isInitialize = false;
private static readonly List<Spawner> _spawners = new List<Spawner>();
private static GameObject _poolingRoot;
/// <summary>
/// 初始化游戏对象池系统
/// </summary>
public static void Initalize()
{
if (_isInitialize)
throw new Exception($"{nameof(UniPooling)} is initialized !");
if (_isInitialize == false)
{
// 创建驱动器
_isInitialize = true;
_poolingRoot = new UnityEngine.GameObject($"[{nameof(UniPooling)}]");
_poolingRoot.AddComponent<UniPoolingDriver>();
UnityEngine.Object.DontDestroyOnLoad(_poolingRoot);
}
}
/// <summary>
/// 更新游戏对象池系统
/// </summary>
internal static void Update()
{
if (_isInitialize)
{
foreach (var spawner in _spawners)
{
spawner.Update();
}
}
}
/// <summary>
/// 销毁游戏对象池系统
/// </summary>
internal static void Destroy()
{
if (_isInitialize)
{
foreach (var spawner in _spawners)
{
spawner.Destroy();
}
_spawners.Clear();
_isInitialize = false;
UniLogger.Log($"{nameof(UniPooling)} destroy all !");
}
}
/// <summary>
/// 创建游戏对象生成器
/// </summary>
/// <param name="packageName">资源包名称</param>
public static Spawner CreateSpawner(string packageName)
{
// 获取资源包
var assetPackage = YooAssets.GetAssetsPackage(packageName);
if (assetPackage == null)
throw new Exception($"Not found asset package : {packageName}");
// 检测资源包初始化状态
if (assetPackage.InitializeStatus == EOperationStatus.None)
throw new Exception($"Asset package {packageName} not initialize !");
if (assetPackage.InitializeStatus == EOperationStatus.Failed)
throw new Exception($"Asset package {packageName} initialize failed !");
if (HasSpawner(packageName))
return GetSpawner(packageName);
Spawner spawner = new Spawner(_poolingRoot, assetPackage);
_spawners.Add(spawner);
return spawner;
}
/// <summary>
/// 获取游戏对象生成器
/// </summary>
/// <param name="packageName">资源包名称</param>
public static Spawner GetSpawner(string packageName)
{
foreach (var spawner in _spawners)
{
if (spawner.PackageName == packageName)
return spawner;
}
UniLogger.Warning($"Not found spawner : {packageName}");
return null;
}
/// <summary>
/// 检测游戏对象生成器是否存在
/// </summary>
/// <param name="packageName">资源包名称</param>
public static bool HasSpawner(string packageName)
{
foreach (var spawner in _spawners)
{
if (spawner.PackageName == packageName)
return true;
}
return false;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 04fd1800aa2e61644893fa7893d93db8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
using UnityEngine;
namespace UniFramework.Pooling
{
internal class UniPoolingDriver : MonoBehaviour
{
void Update()
{
UniPooling.Update();
}
void OnDestroy()
{
UniPooling.Destroy();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f4112e0723ed46c45927cc3498d62e5a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 039eb69f46ea8bf4c873ab10b816da92
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
# UniFramework.Utility
一些工具类。
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f055964b764f8cc41996f3c543307c85
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c3799338015524b47a601024fd574a90
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -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;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a9ba1e57e76e1c3498c1e678e2737ab2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,14 @@
{
"name": "UniUtility",
"rootNamespace": "",
"references": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1ea6b676786131e4095182b742bb64ec
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5079914495c00a74e873f6490a7a5673
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,4 @@
# UniFramework.Window
一个轻量级的基于堆栈的界面系统。
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 32e55b8a0d57de5428a1e06cc0cc87b3
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a933ee98d9388e74dba1a42e77f4f6d8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,70 @@
using YooAsset;
namespace UniFramework.Window
{
public class OpenWindowOperation : GameAsyncOperation
{
private enum ESteps
{
None,
Waiting,
Done,
}
private readonly AssetOperationHandle _handle;
private ESteps _steps = ESteps.None;
internal OpenWindowOperation(AssetOperationHandle handle)
{
_handle = handle;
}
protected override void OnStart()
{
_steps = ESteps.Waiting;
}
protected override void OnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.Waiting)
{
if (_handle.IsValid == false)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{nameof(AssetOperationHandle)} is invalid.";
return;
}
if (_handle.IsDone == false)
return;
if (_handle.AssetObject == null)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"{nameof(AssetOperationHandle.AssetObject)} is null.";
return;
}
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
/// <summary>
/// 等待异步实例化结束
/// </summary>
public void WaitForAsyncComplete()
{
if (_handle != null)
{
if (_steps == ESteps.Done)
return;
_handle.WaitForAsyncComplete();
OnUpdate();
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4607e0d0ccaff3940854224460f93bbd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,325 @@
using System;
using UnityEngine;
using UnityEngine.UI;
using YooAsset;
namespace UniFramework.Window
{
public abstract class UIWindow
{
public const int WINDOW_HIDE_LAYER = 2; // Ignore Raycast
public const int WINDOW_SHOW_LAYER = 5; // UI
internal AssetOperationHandle Handle { private set; get;}
private System.Action<UIWindow> _prepareCallback;
private System.Object[] _userDatas;
private bool _isCreate = false;
private GameObject _panel;
private Canvas _canvas;
private Canvas[] _childCanvas;
private GraphicRaycaster _raycaster;
private GraphicRaycaster[] _childRaycaster;
/// <summary>
/// 面板的Transfrom组件
/// </summary>
public Transform transform
{
get
{
return _panel.transform;
}
}
/// <summary>
/// 面板的游戏对象
/// </summary>
public GameObject gameObject
{
get
{
return _panel;
}
}
/// <summary>
/// 窗口名称
/// </summary>
public string WindowName { private set; get; }
/// <summary>
/// 窗口层级
/// </summary>
public int WindowLayer { private set; get; }
/// <summary>
/// 是否为全屏窗口
/// </summary>
public bool FullScreen { private set; get; }
/// <summary>
/// 自定义数据
/// </summary>
public System.Object UserData
{
get
{
if (_userDatas != null && _userDatas.Length >= 1)
return _userDatas[0];
else
return null;
}
}
/// <summary>
/// 自定义数据集
/// </summary>
public System.Object[] UserDatas
{
get { return _userDatas; }
}
/// <summary>
/// 窗口深度值
/// </summary>
public int Depth
{
get
{
if (_canvas != null)
return _canvas.sortingOrder;
else
return 0;
}
set
{
if (_canvas != null)
{
if (_canvas.sortingOrder == value)
return;
// 设置父类
_canvas.sortingOrder = value;
// 设置子类
int depth = value;
for (int i = 0; i < _childCanvas.Length; i++)
{
var canvas = _childCanvas[i];
if (canvas != _canvas)
{
depth += 5; //注意递增值
canvas.sortingOrder = depth;
}
}
// 虚函数
if (_isCreate)
OnSortDepth(value);
}
}
}
/// <summary>
/// <summary>
/// 窗口可见性
/// </summary>
public bool Visible
{
get
{
if (_canvas != null)
return _canvas.gameObject.layer == WINDOW_SHOW_LAYER;
else
return false;
}
set
{
if (_canvas != null)
{
int setLayer = value ? WINDOW_SHOW_LAYER : WINDOW_HIDE_LAYER;
if (_canvas.gameObject.layer == setLayer)
return;
// 显示设置
_canvas.gameObject.layer = setLayer;
for (int i = 0; i < _childCanvas.Length; i++)
{
_childCanvas[i].gameObject.layer = setLayer;
}
// 交互设置
Interactable = value;
// 虚函数
if (_isCreate)
OnSetVisible(value);
}
}
}
/// <summary>
/// 窗口交互性
/// </summary>
private bool Interactable
{
get
{
if (_raycaster != null)
return _raycaster.enabled;
else
return false;
}
set
{
if (_raycaster != null)
{
_raycaster.enabled = value;
for (int i = 0; i < _childRaycaster.Length; i++)
{
_childRaycaster[i].enabled = value;
}
}
}
}
/// <summary>
/// 是否加载完毕
/// </summary>
internal bool IsLoadDone { get { return Handle.IsDone; } }
/// <summary>
/// 是否准备完毕
/// </summary>
internal bool IsPrepare { private set; get; }
public void Init(string name, int layer, bool fullScreen)
{
WindowName = name;
WindowLayer = layer;
FullScreen = fullScreen;
}
/// <summary>
/// 窗口创建
/// </summary>
public abstract void OnCreate();
/// <summary>
/// 窗口刷新
/// </summary>
public abstract void OnRefresh();
/// <summary>
/// 窗口更新
/// </summary>
public abstract void OnUpdate();
/// <summary>
/// 窗口销毁
/// </summary>
public abstract void OnDestroy();
/// <summary>
/// 当触发窗口的层级排序
/// </summary>
protected virtual void OnSortDepth(int depth) { }
/// <summary>
/// 当因为全屏遮挡触发窗口的显隐
/// </summary>
protected virtual void OnSetVisible(bool visible) { }
internal void TryInvoke(System.Action<UIWindow> prepareCallback, System.Object[] userDatas)
{
_userDatas = userDatas;
if (IsPrepare)
prepareCallback?.Invoke(this);
else
_prepareCallback = prepareCallback;
}
internal void InternalLoad(string location, System.Action<UIWindow> prepareCallback, System.Object[] userDatas)
{
if (Handle != null)
return;
_prepareCallback = prepareCallback;
_userDatas = userDatas;
Handle = YooAssets.LoadAssetAsync<GameObject>(location);
Handle.Completed += Handle_Completed;
}
internal void InternalCreate()
{
if (_isCreate == false)
{
_isCreate = true;
OnCreate();
}
}
internal void InternalRefresh()
{
OnRefresh();
}
internal void InternalUpdate()
{
if(IsPrepare)
{
OnUpdate();
}
}
internal void InternalDestroy()
{
_isCreate = false;
// 注销回调函数
_prepareCallback = null;
// 卸载面板资源
if (Handle != null)
{
Handle.Release();
Handle = null;
}
// 销毁面板对象
if (_panel != null)
{
OnDestroy();
GameObject.Destroy(_panel);
_panel = null;
}
}
private void Handle_Completed(AssetOperationHandle handle)
{
if (handle.AssetObject == null)
return;
// 实例化对象
_panel = handle.InstantiateSync(UniWindow.Desktop.transform);
_panel.transform.localPosition = Vector3.zero;
// 获取组件
_canvas = _panel.GetComponent<Canvas>();
if (_canvas == null)
throw new Exception($"Not found {nameof(Canvas)} in panel {WindowName}");
_canvas.overrideSorting = true;
_canvas.sortingOrder = 0;
_canvas.sortingLayerName = "Default";
// 获取组件
_raycaster = _panel.GetComponent<GraphicRaycaster>();
_childCanvas = _panel.GetComponentsInChildren<Canvas>(true);
_childRaycaster = _panel.GetComponentsInChildren<GraphicRaycaster>(true);
// 通知UI管理器
IsPrepare = true;
_prepareCallback?.Invoke(this);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7e1414cd524a4d24aa5653dba76dd850
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,21 @@
using System.Diagnostics;
namespace UniFramework.Window
{
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);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 53b3b144d6b239e4a8a00b13b18494c0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
{
"name": "UniWindow",
"rootNamespace": "",
"references": [
"GUID:e34a5702dd353724aa315fb8011f08c3"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: e62322788ba70c5428b168602000a586
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,410 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using YooAsset;
namespace UniFramework.Window
{
public static class UniWindow
{
public struct WindowInfo
{
public string WindowName;
public int WindowLayer;
public bool IsLoadDone;
}
private static bool _isInitialize = false;
private static readonly List<UIWindow> _stack = new List<UIWindow>(100);
internal static GameObject Desktop { private set; get; }
/// <summary>
/// 初始化界面系统
/// </summary>
public static void Initalize(GameObject desktop)
{
if (_isInitialize)
throw new Exception($"{nameof(UniWindow)} is initialized !");
if (desktop == null)
throw new ArgumentNullException();
if (_isInitialize == false)
{
// 创建驱动器
_isInitialize = true;
GameObject driver = new UnityEngine.GameObject($"[{nameof(UniWindow)}]");
driver.AddComponent<UniWindowDriver>();
UnityEngine.Object.DontDestroyOnLoad(driver);
Desktop = desktop;
}
}
/// <summary>
/// 更新界面系统
/// </summary>
internal static void Update()
{
if (_isInitialize)
{
int count = _stack.Count;
for (int i = 0; i < _stack.Count; i++)
{
if (_stack.Count != count)
break;
var window = _stack[i];
window.InternalUpdate();
}
}
}
/// <summary>
/// 销毁界面系统
/// </summary>
internal static void Destroy()
{
if (_isInitialize)
{
_isInitialize = false;
CloseAll();
UniLogger.Log($"{nameof(UniWindow)} destroy all !");
}
}
/// <summary>
/// 设置屏幕安全区域(异形屏支持)
/// </summary>
/// <param name="safeRect">安全区域</param>
public static void ApplyScreenSafeRect(Rect safeRect)
{
CanvasScaler scaler = Desktop.GetComponentInParent<CanvasScaler>();
if (scaler == null)
{
UniLogger.Error($"Not found {nameof(CanvasScaler)} !");
return;
}
// Convert safe area rectangle from absolute pixels to UGUI coordinates
float rateX = scaler.referenceResolution.x / Screen.width;
float rateY = scaler.referenceResolution.y / Screen.height;
float posX = (int)(safeRect.position.x * rateX);
float posY = (int)(safeRect.position.y * rateY);
float width = (int)(safeRect.size.x * rateX);
float height = (int)(safeRect.size.y * rateY);
float offsetMaxX = scaler.referenceResolution.x - width - posX;
float offsetMaxY = scaler.referenceResolution.y - height - posY;
// 注意:安全区坐标系的原点为左下角
var rectTrans = Desktop.transform as RectTransform;
rectTrans.offsetMin = new Vector2(posX, posY); //锚框状态下的屏幕左下角偏移向量
rectTrans.offsetMax = new Vector2(-offsetMaxX, -offsetMaxY); //锚框状态下的屏幕右上角偏移向量
}
/// <summary>
/// 模拟IPhoneX异形屏
/// </summary>
public static void SimulateIPhoneXNotchScreen()
{
Rect rect;
if (Screen.height > Screen.width)
{
// 竖屏Portrait
float deviceWidth = 1125;
float deviceHeight = 2436;
rect = new Rect(0f / deviceWidth, 102f / deviceHeight, 1125f / deviceWidth, 2202f / deviceHeight);
}
else
{
// 横屏Landscape
float deviceWidth = 2436;
float deviceHeight = 1125;
rect = new Rect(132f / deviceWidth, 63f / deviceHeight, 2172f / deviceWidth, 1062f / deviceHeight);
}
Rect safeArea = new Rect(Screen.width * rect.x, Screen.height * rect.y, Screen.width * rect.width, Screen.height * rect.height);
ApplyScreenSafeRect(safeArea);
}
/// <summary>
/// 获取窗口堆栈信息
/// </summary>
public static void GetWindowInfos(List<WindowInfo> output)
{
if (output == null)
output = new List<WindowInfo>();
else
output.Clear();
for (int i = 0; i < _stack.Count; i++)
{
var window = _stack[i];
WindowInfo info = new WindowInfo();
info.WindowName = window.WindowName;
info.WindowLayer = window.WindowLayer;
info.IsLoadDone = window.IsLoadDone;
output.Add(info);
}
}
/// <summary>
/// 获取所有层级下顶部的窗口名称
/// </summary>
public static string GetTopWindow()
{
if (_stack.Count == 0)
return string.Empty;
UIWindow topWindow = _stack[_stack.Count - 1];
return topWindow.WindowName;
}
/// <summary>
/// 获取指定层级下顶部的窗口名称
/// </summary>
public static string GetTopWindow(int layer)
{
UIWindow lastOne = null;
for (int i = 0; i < _stack.Count; i++)
{
if (_stack[i].WindowLayer == layer)
lastOne = _stack[i];
}
if (lastOne == null)
return string.Empty;
return lastOne.WindowName;
}
/// <summary>
/// 是否有任意窗口正在加载
/// </summary>
public static bool IsAnyLoading()
{
for (int i = 0; i < _stack.Count; i++)
{
var window = _stack[i];
if (window.IsLoadDone == false)
return true;
}
return false;
}
/// <summary>
/// 查询窗口是否存在
/// </summary>
public static bool HasWindow<T>()
{
return HasWindow(typeof(T));
}
public static bool HasWindow(Type type)
{
return IsContains(type.FullName);
}
/// <summary>
/// 异步打开窗口
/// </summary>
/// <param name="location">资源定位地址</param>
/// <param name="userDatas">用户自定义数据</param>
public static OpenWindowOperation OpenWindowAsync<T>(string location, params System.Object[] userDatas) where T : UIWindow
{
return OpenWindowAsync(typeof(T), location, userDatas);
}
public static OpenWindowOperation OpenWindowAsync(Type type, string location, params System.Object[] userDatas)
{
string windowName = type.FullName;
// 如果窗口已经存在
if (IsContains(windowName))
{
UIWindow window = GetWindow(windowName);
Pop(window); //弹出窗口
Push(window); //重新压入
window.TryInvoke(OnWindowPrepare, userDatas);
var operation = new OpenWindowOperation(window.Handle);
YooAssets.StartOperation(operation);
return operation;
}
else
{
UIWindow window = CreateInstance(type);
Push(window); //首次压入
window.InternalLoad(location, OnWindowPrepare, userDatas);
var operation = new OpenWindowOperation(window.Handle);
YooAssets.StartOperation(operation);
return operation;
}
}
/// <summary>
/// 同步打开窗口
/// </summary>
/// <typeparam name="T">窗口类</typeparam>
/// <param name="location">资源定位地址</param>
/// <param name="userDatas">用户自定义数据</param>
public static OpenWindowOperation OpenWindowSync<T>(string location, params System.Object[] userDatas) where T : UIWindow
{
var operation = OpenWindowAsync(typeof(T), location, userDatas);
operation.WaitForAsyncComplete();
return operation;
}
public static OpenWindowOperation OpenWindowSync(Type type, string location, params System.Object[] userDatas)
{
var operation = OpenWindowAsync(type, location, userDatas);
operation.WaitForAsyncComplete();
return operation;
}
/// <summary>
/// 关闭窗口
/// </summary>
public static void CloseWindow<T>() where T : UIWindow
{
CloseWindow(typeof(T));
}
public static void CloseWindow(Type type)
{
string windowName = type.FullName;
UIWindow window = GetWindow(windowName);
if (window == null)
return;
window.InternalDestroy();
Pop(window);
OnSortWindowDepth(window.WindowLayer);
OnSetWindowVisible();
}
/// <summary>
/// 关闭所有窗口
/// </summary>
public static void CloseAll()
{
for (int i = 0; i < _stack.Count; i++)
{
UIWindow window = _stack[i];
window.InternalDestroy();
}
_stack.Clear();
}
private static void OnWindowPrepare(UIWindow window)
{
OnSortWindowDepth(window.WindowLayer);
window.InternalCreate();
window.InternalRefresh();
OnSetWindowVisible();
}
private static void OnSortWindowDepth(int layer)
{
int depth = layer;
for (int i = 0; i < _stack.Count; i++)
{
if (_stack[i].WindowLayer == layer)
{
_stack[i].Depth = depth;
depth += 100; //注意:每次递增100深度
}
}
}
private static void OnSetWindowVisible()
{
bool isHideNext = false;
for (int i = _stack.Count - 1; i >= 0; i--)
{
UIWindow window = _stack[i];
if (isHideNext == false)
{
window.Visible = true;
if (window.IsPrepare && window.FullScreen)
isHideNext = true;
}
else
{
window.Visible = false;
}
}
}
private static UIWindow CreateInstance(Type type)
{
UIWindow window = Activator.CreateInstance(type) as UIWindow;
WindowAttribute attribute = Attribute.GetCustomAttribute(type, typeof(WindowAttribute)) as WindowAttribute;
if (window == null)
throw new Exception($"Window {type.FullName} create instance failed.");
if (attribute == null)
throw new Exception($"Window {type.FullName} not found {nameof(WindowAttribute)} attribute.");
window.Init(type.FullName, attribute.WindowLayer, attribute.FullScreen);
return window;
}
private static UIWindow GetWindow(string name)
{
for (int i = 0; i < _stack.Count; i++)
{
UIWindow window = _stack[i];
if (window.WindowName == name)
return window;
}
return null;
}
private static bool IsContains(string name)
{
for (int i = 0; i < _stack.Count; i++)
{
UIWindow window = _stack[i];
if (window.WindowName == name)
return true;
}
return false;
}
private static void Push(UIWindow window)
{
// 如果已经存在
if (IsContains(window.WindowName))
throw new System.Exception($"Window {window.WindowName} is exist.");
// 获取插入到所属层级的位置
int insertIndex = -1;
for (int i = 0; i < _stack.Count; i++)
{
if (window.WindowLayer == _stack[i].WindowLayer)
insertIndex = i + 1;
}
// 如果没有所属层级,找到相邻层级
if (insertIndex == -1)
{
for (int i = 0; i < _stack.Count; i++)
{
if (window.WindowLayer > _stack[i].WindowLayer)
insertIndex = i + 1;
}
}
// 如果是空栈或没有找到插入位置
if (insertIndex == -1)
{
insertIndex = 0;
}
// 最后插入到堆栈
_stack.Insert(insertIndex, window);
}
private static void Pop(UIWindow window)
{
// 从堆栈里移除
_stack.Remove(window);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9cd9bf5acfacf214dabf26d7db088067
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
using UnityEngine;
namespace UniFramework.Window
{
internal class UniWindowDriver : MonoBehaviour
{
void Update()
{
UniWindow.Update();
}
void OnDestroy()
{
UniWindow.Destroy();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7468af77f37112d45819be1404c0258d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
using System;
namespace UniFramework.Window
{
[AttributeUsage(AttributeTargets.Class)]
public class WindowAttribute : Attribute
{
/// <summary>
/// 窗口层级
/// </summary>
public int WindowLayer;
/// <summary>
/// 全屏窗口标记
/// </summary>
public bool FullScreen;
public WindowAttribute(int windowLayer, bool fullScreen)
{
WindowLayer = windowLayer;
FullScreen = fullScreen;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 422a90e8b252ae840aca5adb13efb130
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: