UIModule
This commit is contained in:
ALEXTANG
2022-08-26 17:08:45 +08:00
parent 158d6a1cd8
commit 776b84adc2
24 changed files with 1933 additions and 0 deletions

View File

@@ -0,0 +1,300 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngineInternal;
using Object = UnityEngine.Object;
namespace TEngine.Runtime
{
/// <summary>
/// 封装Unity相关的一些通用接口
/// </summary>
public class UnityUtil
{
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
public static Component AddMonoBehaviour(Type type, GameObject go)
{
var comp = go.GetComponent(type);
if (comp == null)
{
comp = go.AddComponent(type);
}
return comp;
}
public static T AddMonoBehaviour<T>(Component comp) where T : Component
{
var ret = comp.GetComponent<T>();
if (ret == null)
{
ret = comp.gameObject.AddComponent<T>();
}
return ret;
}
public static T AddMonoBehaviour<T>(GameObject go) where T : Component
{
var comp = go.GetComponent<T>();
if (comp == null)
{
comp = go.AddComponent<T>();
}
return comp;
}
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
public static void RmvMonoBehaviour(Type type, GameObject go)
{
var comp = go.GetComponent(type);
if (comp != null)
{
UnityEngine.Object.Destroy(comp);
}
}
public static void RmvMonoBehaviour<T>(GameObject go) where T : Component
{
var comp = go.GetComponent<T>();
if (comp != null)
{
UnityEngine.Object.Destroy(comp);
}
}
public static Transform FindChild(Transform transform, string path)
{
var findTrans = transform.Find(path);
if (findTrans != null)
{
return findTrans;
}
return null;
}
public static Transform FindChildByName(Transform transform, string name)
{
if (transform == null)
{
return null;
}
for (int i = 0; i < transform.childCount; i++)
{
var childTrans = transform.GetChild(i);
if (childTrans.name == name)
{
return childTrans;
}
var find = FindChildByName(childTrans, name);
if (find != null)
{
return find;
}
}
return null;
}
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
public static Component FindChildComponent(Type type, Transform transform, string path)
{
var findTrans = transform.Find(path);
if (findTrans != null)
{
return findTrans.gameObject.GetComponent(type);
}
return null;
}
public static T FindChildComponent<T>(Transform transform, string path) where T : Component
{
var findTrans = transform.Find(path);
if (findTrans != null)
{
return findTrans.gameObject.GetComponent<T>();
}
return null;
}
public static void SetLayer(GameObject go, int layer)
{
if (go == null)
{
return;
}
SetLayer(go.transform, layer);
}
public static void SetLayer(Transform trans, int layer)
{
if (trans == null)
{
return;
}
trans.gameObject.layer = layer;
for (int i = 0, imax = trans.childCount; i < imax; ++i)
{
Transform child = trans.GetChild(i);
SetLayer(child, layer);
}
}
public static int RandomRangeInt(int min, int max)
{
return UnityEngine.Random.Range(min, max);
}
public static float RandomRangeFloat(float min, float max)
{
return UnityEngine.Random.Range(min, max);
}
public static Vector2 RandomInsideCircle(float radius)
{
return UnityEngine.Random.insideUnitCircle * radius;
}
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
public static Array CreateUnityArray(Type type, int length)
{
return Array.CreateInstance(type, length);
}
public static T[] CreateUnityArray<T>(int length)
{
return new T[length];
}
public static GameObject Instantiate(GameObject go)
{
if (go != null)
{
return UnityEngine.GameObject.Instantiate(go);
}
return null;
}
public static int GetHashCodeByString(string str)
{
return str.GetHashCode();
}
public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance, int layerMask)
{
return Physics.Raycast(ray, out hitInfo, maxDistance, layerMask);
}
public static List<string> GetRegexMatchGroups(string pattern, string input)
{
List<string> list = new List<string>();
var regexLink = new Regex(pattern);
var links = regexLink.Match(input);
for (var i = 0; i < links.Groups.Count; ++i)
{
list.Add(links.Groups[i].Value);
}
return list;
}
public static void SetMaterialVector3(Material mat, int nameId, Vector3 val)
{
mat.SetVector(nameId, val);
}
public static void GetVectorData(Vector3 val, out float x, out float y, out float z)
{
x = val.x;
y = val.y;
z = val.z;
}
public static void GetVector2Data(Vector2 val, out float x, out float y)
{
x = val.x;
y = val.y;
}
public static bool GetTouchByFingerId(int fingerId, out Touch findTouch)
{
var finded = false;
var touchCnt = Input.touchCount;
findTouch = new Touch();
for (int i = 0; i < touchCnt; i++)
{
var touch = Input.GetTouch(i);
if (touch.fingerId == fingerId)
{
findTouch = touch;
finded = true;
break;
}
}
return finded;
}
public static bool SetAnimatorController(GameObject go, string resPath)
{
//RuntimeAnimatorController rac = (RuntimeAnimatorController)ResourcesManager.Instance.Load<UnityEngine.Object>(resPath);
//if (rac == null)
//{
// Debug.Log("GetAnimator failed path: " + resPath);
// return false;
//}
//var ani = go.GetComponentInChildren<Animator>(true);
//if (ani != null)
//{
// ani.runtimeAnimatorController = rac;
// return true;
//}
return false;
}
public static void SetGameObjectActive(GameObject go, bool active)
{
if (go != null && go.activeSelf != active)
{
go.SetActive(active);
}
}
public static T[] GetComponentsInChildren<T>(GameObject go) where T : UIBehaviour
{
if (go != null)
{
return go.GetComponentsInChildren<T>();
}
return null;
}
public static T GetComponent<T>(GameObject go)
{
if (go != null)
{
return go.GetComponent<T>();
}
return default(T);
}
}
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,7 @@
namespace TEngine.Runtime.UIModule
{
public interface IUIController
{
void RegisterUIEvent();
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0801c753191b47a08c37d1f5dd82e38b
timeCreated: 1661502732

View File

@@ -0,0 +1,533 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace TEngine.Runtime.UIModule
{
public sealed partial class UIManager : TSingleton<UIManager>
{
private Transform m_canvasTrans;
public Canvas m_canvas;
private Dictionary<uint, UIWindow> m_allWindow = new Dictionary<uint, UIWindow>();
/// <summary>
/// 不同显示顺序的的窗口列表
/// </summary>
private UIWindowStack[] m_listWindowStack = new UIWindowStack[(int)WindowStackIndex.StackMax];
/// <summary>
/// 类型到实例的索引
/// </summary>
private static Dictionary<string, UIWindow> m_typeToInst = new Dictionary<string, UIWindow>();
/// <summary>
/// 类型和资源的绑定关系
/// </summary>
private Dictionary<string, string> m_uiType2PrefabPath = new Dictionary<string, string>();
private GameObject m_uiManagerGo;
private Transform m_uiManagerTransform;
private Camera m_uiCamera;
public Camera Camera => m_uiCamera;
public UIManager()
{
m_uiManagerGo = TResources.Load("UI/UIRoot.prefab");
Object.DontDestroyOnLoad(m_uiManagerGo);
m_uiManagerTransform = m_uiManagerGo.transform;
m_uiCamera = UnityUtil.FindChildComponent<Camera>(m_uiManagerTransform, "Camera");
Canvas canvas = m_uiManagerGo.GetComponentInChildren<Canvas>();
if (canvas != null)
{
m_canvas = canvas;
m_canvasTrans = canvas.transform;
}
var windowRoot = m_canvasTrans;
int baseOrder = 1000;
for (int i = 0; i < (int)WindowStackIndex.StackMax; i++)
{
m_listWindowStack[i] = new UIWindowStack();
m_listWindowStack[i].m_stackIndex = (WindowStackIndex)i;
m_listWindowStack[i].m_baseOrder = baseOrder;
m_listWindowStack[i].m_parentTrans = windowRoot;
baseOrder += 1000;
}
CalcCameraRect();
}
void CalcCameraRect()
{
CanvasScaler canvasScale = m_canvas.GetComponent<CanvasScaler>();
if (canvasScale != null)
{
canvasScale.referenceResolution = new Vector2(UISys.DesginWidth, UISys.DesginHeight);
float sceneScale = Screen.width / (float)Screen.height;
float designScale = canvasScale.referenceResolution.x / canvasScale.referenceResolution.y;
canvasScale.matchWidthOrHeight = sceneScale > designScale ? 1 : 0;
}
}
public void OnUpdate()
{
var allList = GetAllWindowList();
for (int i = 0; i < allList.Count; i++)
{
UIWindow window = allList[i];
if (!window.IsDestroyed)
{
window.Update();
}
}
}
private List<UIWindow> m_tmpWindowList = new List<UIWindow>();
private bool m_tmpWindowListDirty = true;
private List<UIWindow> GetAllWindowList()
{
if (m_tmpWindowListDirty)
{
m_tmpWindowList.Clear();
var itr = m_allWindow.GetEnumerator();
while (itr.MoveNext())
{
var kv = itr.Current;
m_tmpWindowList.Add(kv.Value);
}
m_tmpWindowListDirty = false;
}
return m_tmpWindowList;
}
#region Methods
public T ShowWindow<T>(bool isAsync = false) where T : UIWindow, new()
{
string typeName = GetWindowTypeName<T>();
T window = GetUIWindowByType(typeName) as T;
if (window == null)
{
window = new T();
if (!CreateWindowByType(window, typeName, isAsync))
{
return null;
}
}
ShowWindow(window, -1);
return window;
}
public string GetWindowTypeName<T>()
{
string typeName = typeof(T).Name;
return typeName;
}
public string GetWindowTypeName(UIWindow window)
{
string typeName = window.GetType().Name;
return typeName;
}
public void CloseWindow<T>() where T : UIWindow
{
string typeName = GetWindowTypeName<T>();
CloseWindow(typeName);
}
public T GetWindow<T>() where T : UIWindow
{
string typeName = GetWindowTypeName<T>();
UIWindow window = GetUIWindowByType(typeName);
if (window != null)
{
return window as T;
}
return null;
}
public UIWindow GetUIWindowByType(string typeName)
{
UIWindow window;
if (m_typeToInst.TryGetValue(typeName, out window))
{
return window;
}
return null;
}
#endregion
private bool CreateWindowByType(UIWindow window, string typeName, bool async = false)
{
//先判断是否有缓存
GameObject uiGo = null;
string resPath = string.Format("{0}.prefab", GetUIResourcePath(typeName));
if (string.IsNullOrEmpty(resPath))
{
Debug.LogErrorFormat("CreateWindowByType failed, typeName:{0}, cant find respath", typeName);
return false;
}
UIWindowStack windowStack = GetUIWindowStack(window);
if (async)
{
TResources.LoadAsync(resPath, (obj) =>
{
if (obj == null)
{
Debug.LogErrorFormat("CreateWindowByType failed, typeName:{0}, load prefab failed: {1}",
typeName, resPath);
}
if (obj != null && windowStack.m_parentTrans != null)
{
obj.transform.SetParent(windowStack.m_parentTrans);
}
obj.name = typeName;
window.AllocWindowId();
var rectTrans_ = obj.transform as RectTransform;
if (window.NeedCenterUI())
{
rectTrans_.SetMax(); //localPosition = new Vector3(0, 0, 0);
}
rectTrans_.localRotation = Quaternion.identity;
rectTrans_.localScale = Vector3.one;
if (!window.Create(this, obj))
{
Debug.LogErrorFormat("window create failed, typeName:{0}", typeName);
if (obj != null)
{
Object.Destroy(obj);
obj = null;
}
}
m_typeToInst[typeName] = window;
m_allWindow[window.WindowId] = window;
m_tmpWindowListDirty = true;
});
return true;
}
uiGo = TResources.Load(resPath, windowStack.m_parentTrans);
if (uiGo == null)
{
Debug.LogErrorFormat("CreateWindowByType failed, typeName:{0}, load prefab failed: {1}", typeName,
resPath);
//UISys.Mgr.ShowTipMsg(TextDefine.DOWNLOAD_TIP_UI);
//GameEvent.Get<IHomePageUI>().ShowDownloadUI();
return false;
}
uiGo.name = typeName;
window.AllocWindowId();
RectTransform rectTrans = uiGo.transform as RectTransform;
if (window.NeedCenterUI())
{
rectTrans.SetMax(); //localPosition = new Vector3(0, 0, 0);
}
rectTrans.localRotation = Quaternion.identity;
rectTrans.localScale = Vector3.one;
if (!window.Create(this, uiGo))
{
Debug.LogErrorFormat("window create failed, typeName:{0}", typeName);
if (uiGo != null)
{
Object.Destroy(uiGo);
uiGo = null;
}
return false;
}
m_typeToInst[typeName] = window;
m_allWindow[window.WindowId] = window;
m_tmpWindowListDirty = true;
return true;
}
#region MyRegion
private string GetUIResourcePath(string typeName)
{
string resPath;
if (m_uiType2PrefabPath.TryGetValue(typeName, out resPath))
{
return resPath;
}
string path = string.Format("UI/{0}", typeName);
m_uiType2PrefabPath.Add(typeName, path);
return path;
}
private void ShowWindow(UIWindow window, int showIndex)
{
UIWindowStack windowStack = GetUIWindowStack(window);
List<uint> windowList = windowStack.m_windowList;
int resortIndex = -1;
int findIndex = windowList.IndexOf(window.WindowId);
if (findIndex >= 0)
{
windowList.RemoveAt(findIndex);
resortIndex = findIndex;
}
windowList.Add(window.WindowId);
ResortStackUI(windowStack, resortIndex);
ShowTopUI(windowStack);
}
private void ResortStackUI(UIWindowStack stack, int startIdx)
{
if (stack.m_windowList.Count > 0)
{
startIdx = startIdx < 0 ? (stack.m_windowList.Count - 1) : startIdx;
for (int i = startIdx; i < stack.m_windowList.Count; i++)
{
uint windowId = stack.m_windowList[i];
UIWindow window = FindWindow(windowId);
if (window != null)
{
int order;
if (window.IsFixedSortingOrder)
{
order = stack.m_baseOrder + window.FixedAdditionalOrder;
}
else
{
order = stack.m_baseOrder + i * UIWindow.MaxCanvasSortingOrder;
}
window.SortingOrder = order;
}
}
}
}
private void ShowTopUI(UIWindowStack stack)
{
if (stack.m_windowList.Count > 0)
{
bool hasTop = false;
for (int i = stack.m_windowList.Count - 1; i >= 0; i--)
{
uint windowId = stack.m_windowList[i];
UIWindow window = FindWindow(windowId);
if (window != null)
{
if (!hasTop)
{
hasTop = window.IsFullScreen;
window.Show(true);
}
else
{
window.Show(false);
}
}
}
}
OnWindowVisibleChanged();
}
private void OnWindowVisibleChanged()
{
bool isFullScreenMaskscene = false;
for (int i = 0; i < m_listWindowStack.Length && !isFullScreenMaskscene; i++)
{
var stack = m_listWindowStack[i];
if (stack == null)
{
continue;
}
var listWindow = stack.m_windowList;
for (int k = 0; k < listWindow.Count; k++)
{
var winId = listWindow[k];
var win = FindWindow(winId);
if (win == null || !win.Visible)
{
continue;
}
if (win.IsFullScreenMaskScene)
{
isFullScreenMaskscene = true;
break;
}
}
}
//SceneSys.Instance.CameraMgr.SetSceneCameraEnableByUI(true);
}
public UIWindow FindWindow(uint windowId)
{
UIWindow window;
if (m_allWindow.TryGetValue(windowId, out window))
{
return window;
}
return null;
}
public void CloseWindow(string typeName)
{
UIWindow window = GetUIWindowByType(typeName);
if (window != null)
{
CloseWindow(window);
}
}
public void CloseWindow(UIWindow window)
{
if (window.IsDestroyed)
{
return;
}
//刷新窗口order保证新创建的窗口不会出现重叠
UIWindowStack windowStack = GetUIWindowStack(window);
int findIndex = windowStack.FindIndex(window.WindowId);
//window.Destroy();
DestroyWindowObject(window);
ResortStackUI(windowStack, findIndex);
ShowTopUI(windowStack);
}
private void DestroyWindowObject(UIWindow window)
{
string typeName = window.GetType().Name;
UIWindow typeWindow = null;
if (m_typeToInst.TryGetValue(typeName, out typeWindow) && typeWindow == window)
{
m_typeToInst.Remove(typeName);
}
uint windowId = window.WindowId;
m_allWindow.Remove(windowId);
UIWindowStack windowStack = GetUIWindowStack(window);
windowStack.m_windowList.Remove(windowId);
window.Destroy();
m_tmpWindowListDirty = true;
}
private int GetIndexByWindowType(UIWindowType windowType)
{
if (windowType == UIWindowType.WindowTop)
{
return (int)WindowStackIndex.StackTop;
}
return (int)WindowStackIndex.StackNormal;
}
public UIWindowStack GetUIWindowStack(UIWindow window)
{
int index = GetIndexByWindowType(window.GetWindowType());
return m_listWindowStack[index];
}
public UIWindow GetWindowById(uint windowId)
{
return FindWindow(windowId);
}
public UIWindowStack GetUIWindowStack(UIWindowType windowType)
{
int index = GetIndexByWindowType(windowType);
return m_listWindowStack[index];
}
#endregion
#region
/// <summary>
/// 给控件添加自定义事件监听
/// </summary>
/// <param name="control">控件对象</param>
/// <param name="type">事件类型</param>
/// <param name="callback">事件的响应函数</param>
public static void AddCustomEventListener(UIBehaviour control, EventTriggerType type,
UnityAction<BaseEventData> callback)
{
EventTrigger trigger = control.GetComponent<EventTrigger>();
if (trigger == null)
{
trigger = control.gameObject.AddComponent<EventTrigger>();
}
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = type;
entry.callback.AddListener(callback);
trigger.triggers.Add(entry);
}
public bool GetMouseDownUiPos(out Vector3 screenPos)
{
bool hadMouseDown = false;
Vector3 mousePos = Vector3.zero;
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
mousePos = Input.mousePosition;
hadMouseDown = Input.GetMouseButton(0);
#else
if (Input.touchCount > 0)
{
mousePos = Input.GetTouch(0).position;
hadMouseDown = true;
}
else
{
hadMouseDown = false;
}
#endif
Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(m_canvasTrans as RectTransform, Input.mousePosition,
m_uiCamera, out pos);
screenPos = m_canvasTrans.TransformPoint(pos);
return hadMouseDown;
}
#endregion
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e74405722cde4618ab9345bfee06bb82
timeCreated: 1661503069

View File

@@ -0,0 +1,34 @@
using System.Collections.Generic;
namespace TEngine.Runtime.UIModule
{
public partial class UISys
{
private List<IUIController> m_listController = new List<IUIController>();
public void RegisterAllController()
{
//AddController<LoadingUIController>();
}
private void AddController<T>() where T : IUIController, new()
{
for (int i = 0; i < m_listController.Count; i++)
{
var type = m_listController[i].GetType();
if (type == typeof(T))
{
Log.Error(Utility.Text.Format("repeat controller type: {0}", typeof(T).Name));
return;
}
}
var controller = new T();
m_listController.Add(controller);
controller.RegisterUIEvent();
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1a56516dc01941788d6b2444486ba2dc
timeCreated: 1661502668

View File

@@ -0,0 +1,27 @@
namespace TEngine.Runtime.UIModule
{
public partial class UISys:BehaviourSingleton<UISys>
{
public static int DesginWidth => 750;
public static int DesginHeight => 1624;
public static UIManager Mgr
{
get { return UIManager.Instance; }
}
public override void Active()
{
base.Active();
RegisterAllController();
}
public override void Update()
{
base.Update();
UIManager.Instance.OnUpdate();
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7d083df9934145c38db443762bb72060
timeCreated: 1661502362

View File

@@ -0,0 +1,33 @@
using System.Collections.Generic;
using UnityEngine;
namespace TEngine.Runtime.UIModule
{
public enum WindowStackIndex
{
StackNormal = 0,
StackTop = 1,
StackMax
};
public class UIWindowStack
{
public WindowStackIndex m_stackIndex;
public int m_baseOrder = 0;
public List<uint> m_windowList = new List<uint>();
public Transform m_parentTrans;
public int FindIndex(uint windowId)
{
for (int i = 0; i < m_windowList.Count; i++)
{
if (m_windowList[i] == windowId)
{
return i;
}
}
return -1;
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0f7edbd113f347cd879fb95370b9e8f5
timeCreated: 1661503317

View File

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

View File

@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace TEngine.Runtime.UIModule
{
public class UIBase
{
protected GameObject m_go;
protected RectTransform m_transform;
protected string m_name;
protected bool m_destroyed = true;
private GameEventMgr m_eventMgr;
protected GameEventMgr EventMgr
{
get
{
if (m_eventMgr == null)
{
m_eventMgr = GameEventMgr.Instance;
}
return m_eventMgr;
}
}
public bool IsDestroyed
{
get { return m_destroyed; }
}
public bool IsCreated
{
get { return !IsDestroyed; }
}
public RectTransform transform
{
get { return m_transform; }
}
public GameObject gameObject
{
get { return m_go; }
}
public string name
{
get
{
if (string.IsNullOrEmpty(m_name))
{
m_name = GetType().Name;
}
return m_name;
}
}
#region Event
private Dictionary<int, Delegate> m_eventTable = new Dictionary<int, Delegate>();
protected void ClearAllRegisterEvent()
{
var element = m_eventTable.GetEnumerator();
while (element.MoveNext())
{
var m_event = element.Current.Value;
//GameEventMgr.Instance.RemoveEventListener(element.Current.Key, m_event);
}
m_eventTable.Clear();
}
protected void AddUIEvent(int eventType, Action handler)
{
m_eventTable.Add(eventType, handler);
EventMgr.AddEventListener(eventType, handler);
}
protected void AddUIEvent<T>(int eventType, Action<T> handler)
{
m_eventTable.Add(eventType, handler);
EventMgr.AddEventListener(eventType, handler);
}
protected void AddUIEvent<T, U>(int eventType, Action<T, U> handler)
{
m_eventTable.Add(eventType, handler);
EventMgr.AddEventListener(eventType, handler);
}
protected void AddUIEvent<T, U, V>(int eventType, Action<T, U, V> handler)
{
m_eventTable.Add(eventType, handler);
EventMgr.AddEventListener(eventType, handler);
}
#endregion
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fbb040a83c294beab9e514d9c2360841
timeCreated: 1661503401

View File

@@ -0,0 +1,270 @@
using UnityEngine;
using UnityEngine.UI;
namespace TEngine.Runtime.UIModule
{
public enum UIWindowType
{
/// <summary> 普通窗口 </summary>
WindowNormal,
/// <summary> 置顶窗口 </summary>
WindowTop,
/// <summary> 模态窗口 </summary>
WindowModel
}
public enum ModalType
{
/// <summary> 普通模态 </summary>
NormalType,
/// <summary> 透明模态 </summary>
TransparentType,
/// <summary> 普通状态且有关闭功能 </summary>
NormalHaveClose,
/// <summary> 透明状态且有关闭功能 </summary>
TransparentHaveClose,
/// <summary> 非模态 </summary>
NoneType,
}
public class UIWindow : UIWindowBase
{
#region
private bool m_isClosed = false;
private bool m_isCreating = false;
private Image m_modalImage;
private float m_modalAlpha = 0.86f;
/// <summary>
/// 是否固定SortingOrder
/// </summary>
public virtual bool IsFixedSortingOrder
{
get { return false; }
}
public virtual bool NeedCenterUI()
{
return true;
}
/// <summary>
/// 窗口Id
/// </summary>
private uint m_windowId = 0;
/// <summary>
/// 窗口Id
/// </summary>
public uint WindowId
{
get { return m_windowId; }
}
private static uint m_nextWindowId = 0;
public virtual bool IsFullScreen
{
get { return false; }
}
public virtual bool IsFullScreenMaskScene
{
get { return false; }
}
/// <summary>
/// 一个界面中最大sortOrder值
/// </summary>
public const int MaxCanvasSortingOrder = 50;
/// <summary>
/// SortingOrder = stack.m_baseOrder + FixedAdditionalOrder
/// </summary>
public virtual int FixedAdditionalOrder
{
get { return UIWindow.MaxCanvasSortingOrder; }
}
public int SortingOrder
{
get
{
if (m_canvas != null)
{
return m_canvas.sortingOrder;
}
return 0;
}
set
{
if (m_canvas != null)
{
int oldOrder = m_canvas.sortingOrder;
if (oldOrder != value)
{
var listCanvas = gameObject.GetComponentsInChildren<Canvas>(true);
for (int i = 0; i < listCanvas.Length; i++)
{
var childCanvas = listCanvas[i];
childCanvas.sortingOrder = value + (childCanvas.sortingOrder - oldOrder);
}
m_canvas.sortingOrder = value;
_OnSortingOrderChg();
}
}
}
}
#endregion
public void AllocWindowId()
{
if (m_nextWindowId == 0)
{
m_nextWindowId++;
}
m_windowId = m_nextWindowId++;
}
#region virtual function
public virtual UIWindowType GetWindowType()
{
return UIWindowType.WindowNormal;
}
#endregion
#region Call From UIManager
public bool Create(UIManager uiMgr, GameObject uiGo)
{
if (IsCreated)
{
return true;
}
m_isClosed = false;
if (!CreateBase(uiGo, true))
{
return false;
}
if (m_canvas == null)
{
Debug.LogErrorFormat("{0} have not a canvas!!", this.ToString());
Destroy();
return false;
}
m_ownUIManager = uiMgr;
m_firstVisible = false;
if (m_canvas != null)
{
m_canvas.overrideSorting = true;
}
ScriptGenerator();
BindMemberProperty();
RegisterEvent();
m_isCreating = true;
OnCreate();
m_isCreating = false;
if (m_isClosed)
{
Destroy();
return false;
}
SetModalState(GetModalType());
return true;
}
public virtual ModalType GetModalType()
{
if (IsFullScreen || GetWindowType() == UIWindowType.WindowTop)
{
return ModalType.TransparentType;
}
return ModalType.NormalType;
}
private void SetModalState(ModalType type)
{
var canClose = false;
switch (type)
{
case ModalType.NormalType:
{
m_modalAlpha = 0f;
break;
}
case ModalType.NormalHaveClose:
{
canClose = true;
break;
}
case ModalType.TransparentType:
{
m_modalAlpha = 0.01f;
break;
}
case ModalType.TransparentHaveClose:
{
m_modalAlpha = 0.01f;
canClose = true;
break;
}
default:
{
m_modalAlpha = 0f;
break;
}
}
if (m_modalAlpha > 0)
{
string path = "UI/ModalSprite.prefab";
GameObject modal = TResources.Load(path);
modal.transform.SetParent(transform);
modal.transform.SetAsFirstSibling();
modal.transform.localScale = Vector3.one;
modal.transform.localPosition = Vector3.zero;
if (canClose)
{
var button = UnityUtil.AddMonoBehaviour<Button>(modal);
button.onClick.AddListener(Close);
}
m_modalImage = UnityUtil.AddMonoBehaviour<Image>(modal);
m_modalImage.color = new Color(0, 0, 0, m_modalAlpha);
}
}
public virtual void Close()
{
if (m_isCreating)
{
m_isClosed = true;
return;
}
var mgr = UIMgr;
if (mgr != null)
{
mgr.CloseWindow(this);
}
}
#endregion
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: faa500d8fde54fc6a516156f74bfff5b
timeCreated: 1661504497

View File

@@ -0,0 +1,472 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace TEngine.Runtime.UIModule
{
/// <summary>
/// UI组件类型
/// </summary>
public enum UIWindowBaseType
{
/// <summary>
/// None类型
/// </summary>
None,
/// <summary>
/// 窗体类型
/// </summary>
Window,
/// <summary>
/// 组件类型
/// </summary>
Widget,
}
public class UIWindowBase : UIBase
{
/// <summary>
/// 所属的window
/// </summary>
protected UIWindowBase m_parent = null;
protected Canvas m_canvas;
private List<UIWindowBase> m_listChild = null;
private List<UIWindowBase> m_listUpdateChild = null;
private bool m_updateListValid = false;
/// <summary>
/// 是否首次显示过
/// </summary>
protected bool m_firstVisible = false;
/// <summary>
/// 当前是否显示
/// </summary>
private bool m_visible = false;
public bool Visible
{
get { return m_visible; }
}
public UIWindowBase Parent
{
get { return m_parent; }
}
protected UIManager m_ownUIManager = null;
protected UIManager UIMgr
{
get
{
if (m_ownUIManager == null && m_parent != null)
{
return m_parent.UIMgr;
}
return m_ownUIManager;
}
}
public virtual UIWindowBaseType BaseType
{
get { return UIWindowBaseType.None; }
}
#region
/// <summary>
/// 创建对象
/// </summary>
/// <param name="go">GameObject</param>
/// <param name="bindGo">是否进性绑定</param>
/// <returns></returns>
protected bool CreateBase(GameObject go, bool bindGo)
{
if (!m_destroyed)
{
Debug.LogErrorFormat("UIBase has created: {0}", go.name);
return false;
}
if (go == null)
{
return false;
}
m_destroyed = false;
m_go = go;
m_transform = go.GetComponent<RectTransform>();
m_canvas = gameObject.GetComponent<Canvas>();
var canvas = gameObject.GetComponentsInChildren<Canvas>(true);
for (var i = 0; i < canvas.Length; i++)
{
var canva = canvas[i];
canva.additionalShaderChannels = AdditionalCanvasShaderChannels.TexCoord1;
}
if (m_transform == null)
{
Debug.LogErrorFormat("{0} ui base element need to be RectTransform", go.name);
}
return true;
}
protected void DestroyAllChild()
{
//销毁子对象
if (m_listChild != null)
{
for (int i = 0; i < m_listChild.Count; i++)
{
var child = m_listChild[i];
child.Destroy();
}
m_listChild.Clear();
}
}
public void Destroy()
{
if (IsDestroyed)
{
return;
}
m_destroyed = true;
OnDestroy();
DestroyAllChild();
if (m_parent != null)
{
m_parent.RmvChild(this);
m_parent = null;
}
if (m_go != null)
{
Object.Destroy(m_go);
m_go = null;
}
m_transform = null;
}
#endregion
#region
/// <summary> 脚本生成的代码 </summary>
protected virtual void ScriptGenerator()
{
}
/// <summary>
/// 绑定代码和prefab之间元素的关系
/// </summary>
protected virtual void BindMemberProperty()
{
}
protected virtual void RegisterEvent()
{
}
private bool m_hasOverrideUpdate = true;
protected virtual void OnUpdate()
{
m_hasOverrideUpdate = false;
}
/// <summary>
/// 界面创建出来的时候调用,被覆盖不可见不会重复触发
/// </summary>
protected virtual void OnCreate()
{
}
protected virtual void OnDestroy()
{
}
/// <summary>
/// 创建出来首次visible
/// 用来播放一些显示动画之类的
/// </summary>
protected virtual void OnFirstVisible()
{
}
/// <summary>
/// 当显示出来的时候调用
/// 包括首次初始化后显示和上面的界面消失后重新恢复显示
/// </summary>
protected virtual void OnVisible()
{
}
/// <summary>
/// 界面不可见的时候调用
/// 当被上层全屏界面覆盖后,也会触发一次隐藏
/// </summary>
protected virtual void OnHidden()
{
}
protected void _OnSortingOrderChg()
{
if (m_listChild != null)
{
for (int i = 0; i < m_listChild.Count; i++)
{
if (m_listChild[i].m_visible)
{
m_listChild[i]._OnSortingOrderChg();
}
}
}
OnSortingOrderChg();
}
protected virtual void OnSortingOrderChg()
{
}
#endregion
public void AddChild(UIWindowBase child)
{
if (m_listChild == null)
{
m_listChild = new List<UIWindowBase>();
}
m_listChild.Add(child);
MarkListChanged();
}
public void RmvChild(UIWindowBase child)
{
//如果已经销毁了或者销毁过程中,那么不掉用删除
if (m_destroyed)
{
return;
}
if (m_listChild != null)
{
if (m_listChild.Remove(child))
{
MarkListChanged();
}
}
}
/// <summary>
/// 重新整理update和lateupdate的调用缓存
/// </summary>
private void MarkListChanged()
{
m_updateListValid = false;
if (m_parent != null)
{
m_parent.MarkListChanged();
}
}
#region
protected Coroutine StartCoroutine(IEnumerator routine)
{
return MonoUtility.StartCoroutine(routine);
}
protected void StopCoroutine(Coroutine cort)
{
MonoUtility.StopCoroutine(cort);
}
#endregion
#region
public Transform FindChild(string path)
{
return UnityUtil.FindChild(transform, path);
}
public Transform FindChild(Transform _transform, string path)
{
return UnityUtil.FindChild(_transform, path);
}
public T FindChildComponent<T>(string path) where T : Component
{
return UnityUtil.FindChildComponent<T>(transform, path);
}
public T FindChildComponent<T>(Transform _transform, string path) where T : Component
{
return UnityUtil.FindChildComponent<T>(_transform, path);
}
public void Show(bool visible)
{
// 加个保护
if (m_destroyed || gameObject == null)
{
return;
}
if (m_visible != visible)
{
m_visible = visible;
if (visible)
{
gameObject.SetActive(true);
_OnVisible();
}
else
{
_OnHidden();
if (gameObject == null)
{
Debug.LogErrorFormat("ui bug, hiden destory gameobject: {0}", name);
}
else
{
gameObject.SetActive(false);
}
}
MarkListChanged();
}
}
protected void _OnVisible()
{
if (m_listChild != null)
{
for (int i = 0; i < m_listChild.Count; i++)
{
var child = m_listChild[i];
if (child.gameObject.activeInHierarchy)
{
child._OnVisible();
}
}
}
if (!m_firstVisible)
{
m_firstVisible = true;
OnFirstVisible();
}
OnVisible();
}
protected void _OnHidden()
{
if (m_listChild != null)
{
for (int i = 0; i < m_listChild.Count; i++)
{
var child = m_listChild[i];
if (child.gameObject.activeInHierarchy)
{
child._OnHidden();
}
}
}
OnHidden();
}
/// <summary>
/// 返回是否有必要下一帧继续执行
/// </summary>
/// <returns></returns>
public bool Update()
{
if (!m_visible || m_destroyed)
{
return false;
}
List<UIWindowBase> listNextUpdateChild = null;
if (m_listChild != null && m_listChild.Count > 0)
{
listNextUpdateChild = m_listUpdateChild;
var updateListValid = m_updateListValid;
List<UIWindowBase> listChild = null;
if (!updateListValid)
{
if (listNextUpdateChild == null)
{
listNextUpdateChild = new List<UIWindowBase>();
m_listUpdateChild = listNextUpdateChild;
}
else
{
listNextUpdateChild.Clear();
}
listChild = m_listChild;
}
else
{
listChild = listNextUpdateChild;
}
for (int i = 0; i < listChild.Count; i++)
{
var window = listChild[i];
var needValid = window.Update();
if (!updateListValid && needValid)
{
listNextUpdateChild.Add(window);
}
}
if (!updateListValid)
{
m_updateListValid = true;
}
}
bool needUpdate = false;
if (listNextUpdateChild == null || listNextUpdateChild.Count <= 0)
{
m_hasOverrideUpdate = true;
OnUpdate();
needUpdate = m_hasOverrideUpdate;
}
else
{
OnUpdate();
needUpdate = true;
}
return needUpdate;
}
#endregion
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fb696c30797a4467a4f1f3ad0e425474
timeCreated: 1661504101

View File

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

View File

@@ -0,0 +1,83 @@
using UnityEngine;
namespace TEngine.Runtime.UIModule
{
public static class CanvasUtil
{
public static void SetMax(this RectTransform rectTransform)
{
if (rectTransform == null)
{
return;
}
rectTransform.localPosition = new Vector3(0, 0, 0);
rectTransform.localRotation = Quaternion.identity;
rectTransform.localScale = Vector3.one;
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 0);
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 0);
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
}
/// <summary>
/// 调整 RectTransform 组件中的 Left、Bottom 属性
/// </summary>
/// <param name="rt">引用目标 RectTransform 对象</param>
/// <param name="left">Left值</param>
/// <param name="bottom">Bottom值</param>
public static void LeftBottom(RectTransform rectTransform, float left, float bottom)
{
Vector2 size = rectTransform.rect.size;
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, left, size.x);
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, bottom, size.y);
}
/// <summary>
/// 调整 RectTransform 组件中的 Left、Top 属性
/// </summary>
/// <param name="rt"></param>
/// <param name="left">Left值</param>
/// <param name="top">Top值</param>
public static void LeftTop(RectTransform rectTransform, float left, float top)
{
Vector2 size = rectTransform.rect.size;
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, left, size.x);
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, top, size.y);
}
/// <summary>
/// 调整 RectTransform 组件中的 Right、Bottom 属性
/// </summary>
/// <param name="rt"></param>
/// <param name="right">Right值</param>
/// <param name="bottom">Bottom值</param>
public static void RightBottom(RectTransform rectTransform, float right, float bottom)
{
Vector2 size = rectTransform.rect.size;
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, right, size.x);
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, bottom, size.y);
}
/// <summary>
/// 调整 RectTransform 组件中的 Right、Top 属性
/// </summary>
/// <param name="rt"></param>
/// <param name="right">Right值</param>
/// <param name="top">Top值</param>
public static void RightTop(RectTransform rectTransform, float right, float top)
{
Vector2 size = rectTransform.rect.size;
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, right, size.x);
rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, top, size.y);
}
public static void SetCenter(this RectTransform rectTransform, float x = 0, float y = 0)
{
rectTransform.localPosition = new Vector3(0, 0, 0);
rectTransform.localRotation = Quaternion.identity;
rectTransform.localScale = Vector3.one;
Vector2 size = rectTransform.rect.size;
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, size.x);
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, size.y);
rectTransform.localPosition = new Vector2(x, y);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 52c033cf230d4b5a8ab058ffb1d865c7
timeCreated: 1661504812