This commit is contained in:
2025-09-18 18:25:40 +08:00
parent 8ee325cc01
commit ce06ca8571
220 changed files with 165196 additions and 21 deletions
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dfe5d63d6291646498e52273c1322822
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,292 @@
using System;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;
namespace SkierFramework
{
/* 获取内置图片
* AssetDatabase.GetBuiltinExtraResource
* "UI/Skin/UISprite.psd"
"UI/Skin/Background.psd"
"UI/Skin/InputFieldBackground.psd"
"UI/Skin/Knob.psd"
"UI/Skin/Checkmark.psd"
"UI/Skin/DropdownArrow.psd"
"UI/Skin/UIMask.psd"
*/
public class OverrideUICreate
{
[MenuItem("GameObject/UI/Image", true)]
public static void IgnoreImage()
{
}
[MenuItem("GameObject/UI/Image.")]
public static void CreateImage()
{
var image = Create<Image>();
image.raycastTarget = false;
image.maskable = image.GetComponentInParent<RectMask2D>() != null || image.GetComponentInParent<Mask>() != null;
image.gameObject.SetLayerRecursively(Layer.UI);
}
[MenuItem("GameObject/UI/Raw Image", true)]
public static void IgnoreRawImage()
{
}
[MenuItem("GameObject/UI/RawImage")]
public static void CreateRawImage()
{
var image = Create<RawImage>();
image.raycastTarget = false;
image.maskable = image.GetComponentInParent<RectMask2D>() != null || image.GetComponentInParent<Mask>() != null;
image.gameObject.SetLayerRecursively(Layer.UI);
}
[MenuItem("GameObject/UI/Button")]
public static void CreateButton()
{
var image = Create<Image>("Button");
var button = image.AddComponent<Button>();
image.maskable = image.GetComponentInParent<RectMask2D>() != null || image.GetComponentInParent<Mask>() != null;
image.rectTransform.sizeDelta = new Vector2(160, 30);
image.gameObject.SetLayerRecursively(Layer.UI);
}
[MenuItem("GameObject/UI/Text - TextMeshPro", true)]
public static void IgnoreTextMeshPro()
{
}
[MenuItem("GameObject/UI/Text - TextMeshPro")]
public static void CreateTextMeshPro()
{
var textMeshPro = Create<TextMeshProUGUI>("Text");
textMeshPro.raycastTarget = false;
textMeshPro.color = Color.black;
textMeshPro.maskable = textMeshPro.GetComponentInParent<RectMask2D>() != null || textMeshPro.GetComponentInParent<Mask>() != null;
textMeshPro.gameObject.SetLayerRecursively(Layer.UI);
}
[MenuItem("GameObject/UI/Button - TextMeshPro", true)]
public static void IgnoreButtonTextMeshPro()
{
}
[MenuItem("GameObject/UI/Button - TextMeshPro")]
public static void CreateButtonTextMeshPro()
{
var image = Create<Image>("Button");
var button = image.AddComponent<Button>();
var textMeshPro = Create<TextMeshProUGUI>("Text", button.transform);
textMeshPro.raycastTarget = false;
textMeshPro.maskable = textMeshPro.GetComponentInParent<RectMask2D>() != null || textMeshPro.GetComponentInParent<Mask>() != null;
textMeshPro.text = "Button";
textMeshPro.alignment = TextAlignmentOptions.Center;
textMeshPro.alignment = TextAlignmentOptions.Midline;
textMeshPro.rectTransform.anchorMin = Vector3.zero;
textMeshPro.rectTransform.anchorMax = Vector3.one;
textMeshPro.rectTransform.sizeDelta = Vector2.zero;
textMeshPro.color = Color.black;
textMeshPro.fontSize = 24;
image.maskable = textMeshPro.maskable;
image.rectTransform.sizeDelta = new Vector2(160, 30);
image.gameObject.SetLayerRecursively(Layer.UI);
}
#region ScrollRect
[MenuItem("GameObject/UI/Scroll View", true)]
public static void IgnoreScrollView()
{
}
[MenuItem("GameObject/UI/UIScrollView")]
public static ScrollRect CreateScrollView()
{
var image = Create<Image>("UIScrollView");
image.raycastTarget = true;
image.maskable = false;
image.rectTransform.sizeDelta = new Vector2(200, 200);
var scrollRect = image.AddComponent<ScrollRect>();
var uIScrollView = image.AddComponent<UIScrollView>();
var viewportImage = Create<Image>("Viewport", uIScrollView.transform);
viewportImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UIMask.psd");
viewportImage.type = Image.Type.Sliced;
viewportImage.raycastTarget = true;
viewportImage.maskable = true;
var viewport = viewportImage.transform as RectTransform;
viewport.AddComponent<RectMask2D>();
viewport.anchorMin = Vector2.zero;
viewport.anchorMax = Vector2.one;
viewport.pivot = new Vector2(0, 1);
viewport.sizeDelta = Vector2.zero;
viewport.anchoredPosition = Vector2.zero;
scrollRect.viewport = viewport;
var content = Create<RectTransform>("Content", viewport);
content.anchorMin = new Vector2(0, 1);
content.anchorMax = new Vector2(1, 1);
content.pivot = new Vector2(0, 1);
content.sizeDelta = new Vector2(0, 300);
content.anchoredPosition = Vector2.zero;
scrollRect.content = content;
uIScrollView.m_ScrollRect = scrollRect;
uIScrollView.m_Content = content;
scrollRect.gameObject.SetLayerRecursively(Layer.UI);
return scrollRect;
}
[MenuItem("GameObject/UI/UIScrollView - Horizontal")]
public static void CreateScrollViewHorizontal()
{
var scrollRect = CreateScrollView();
scrollRect.horizontalScrollbar = CreateScrollBar("Scrollbar Horizontal", scrollRect.transform);
scrollRect.horizontalScrollbar.direction = Scrollbar.Direction.LeftToRight;
scrollRect.verticalScrollbarVisibility = scrollRect.horizontalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
scrollRect.verticalScrollbarSpacing = scrollRect.horizontalScrollbarSpacing = -3;
var uiScrollView = scrollRect.GetComponent<UIScrollView>();
uiScrollView.m_AxisType = RectTransform.Axis.Horizontal;
uiScrollView.m_AlignType = AlignType.Left;
scrollRect.gameObject.SetLayerRecursively(Layer.UI);
}
[MenuItem("GameObject/UI/UIScrollView - Vertical")]
public static void CreateScrollViewVertical()
{
var scrollRect = CreateScrollView();
scrollRect.verticalScrollbar = CreateScrollBar("Scrollbar Vertical", scrollRect.transform);
var verticalRect = scrollRect.verticalScrollbar.transform as RectTransform;
verticalRect.anchorMin = new Vector2(1, 0);
verticalRect.anchorMax = new Vector2(1, 1);
verticalRect.pivot = new Vector2(1, 1);
verticalRect.sizeDelta = new Vector2(20, 0);
verticalRect.anchoredPosition = Vector2.zero;
scrollRect.verticalScrollbar.direction = Scrollbar.Direction.BottomToTop;
scrollRect.verticalScrollbarVisibility = scrollRect.horizontalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
scrollRect.verticalScrollbarSpacing = scrollRect.horizontalScrollbarSpacing = -3;
scrollRect.gameObject.SetLayerRecursively(Layer.UI);
}
[MenuItem("GameObject/UI/UIScrollView - All")]
public static void CreateScrollViewAll()
{
var scrollRect = CreateScrollView();
scrollRect.horizontalScrollbar = CreateScrollBar("Scrollbar Horizontal", scrollRect.transform);
scrollRect.horizontalScrollbar.direction = Scrollbar.Direction.LeftToRight;
scrollRect.verticalScrollbar = CreateScrollBar("Scrollbar Vertical", scrollRect.transform);
var verticalRect = scrollRect.verticalScrollbar.transform as RectTransform;
verticalRect.anchorMin = new Vector2(1, 0);
verticalRect.anchorMax = new Vector2(1, 1);
verticalRect.pivot = new Vector2(1, 1);
verticalRect.sizeDelta = new Vector2(20, 0);
verticalRect.anchoredPosition = Vector2.zero;
scrollRect.verticalScrollbar.direction = Scrollbar.Direction.BottomToTop;
scrollRect.verticalScrollbarVisibility = scrollRect.horizontalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
scrollRect.verticalScrollbarSpacing = scrollRect.horizontalScrollbarSpacing = -3;
scrollRect.gameObject.SetLayerRecursively(Layer.UI);
}
public static Scrollbar CreateScrollBar(string name, Transform parent)
{
var verticalScorllImage = Create<Image>(name, parent);
verticalScorllImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Background.psd");
verticalScorllImage.type = Image.Type.Sliced;
var verticalScroll = verticalScorllImage.AddComponent<Scrollbar>();
var verticalRect = verticalScroll.transform as RectTransform;
verticalRect.anchorMin = Vector2.zero;
verticalRect.anchorMax = new Vector2(1, 0);
verticalRect.pivot = Vector2.zero;
verticalRect.sizeDelta = new Vector2(0, 20);
verticalRect.anchoredPosition = Vector2.zero;
var handle = Create<Image>("Handle", verticalRect.transform);
handle.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd");
handle.type = Image.Type.Sliced;
handle.rectTransform.anchorMin = Vector2.zero;
handle.rectTransform.anchorMax = Vector2.one;
handle.rectTransform.sizeDelta = Vector2.zero;
handle.rectTransform.anchoredPosition = Vector2.zero;
verticalScroll.handleRect = handle.rectTransform;
return verticalScroll;
}
#endregion
[MenuItem("GameObject/UI/Slider", true)]
public static void IgnoreSlider()
{
}
[MenuItem("GameObject/UI/Slider.")]
public static void CreateSlider()
{
var image = Create<Image>("Slider");
image.color = Color.grey;
image.rectTransform.sizeDelta = new Vector2(160, 20);
var slider = image.AddComponent<Slider>();
slider.interactable = false;
slider.transition = Selectable.Transition.None;
var fill = Create<Image>("Fill", slider.transform);
fill.rectTransform.anchorMin = Vector2.zero;
fill.rectTransform.anchorMax = new Vector2(0, 1);
fill.rectTransform.sizeDelta = Vector2.zero;
fill.rectTransform.anchoredPosition = Vector2.zero;
slider.fillRect = fill.rectTransform;
var handle = Create<Image>("Handle", slider.transform);
handle.rectTransform.anchorMin = Vector2.zero;
handle.rectTransform.anchorMax = new Vector2(0, 1);
handle.rectTransform.sizeDelta = new Vector2(20, 0);
handle.rectTransform.anchoredPosition = Vector2.zero;
handle.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Knob.psd");
slider.handleRect = handle.rectTransform;
image.gameObject.SetLayerRecursively(Layer.UI);
}
public static T Create<T>(string name = null, Transform parent = null) where T : Component
{
if (string.IsNullOrEmpty(name))
name = typeof(T).Name;
GameObject go = new GameObject(name);
if (parent == null)
{
go.transform.SetParent(Selection.activeTransform);
Selection.activeGameObject = go;
}
else
{
go.transform.SetParent(parent);
}
go.transform.localScale = Vector3.one;
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = Quaternion.identity;
return go.AddComponent<T>();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5b2cf4ddaea9fe1499bfdd7e4516b3b2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b8cd8920119b49bc95c6755ae94d1b26
timeCreated: 1758179166
@@ -0,0 +1,41 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenAlpha))]
public class TweenAlphaEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenAlpha tw = target as TweenAlpha;
GUI.changed = false;
var from = EditorGUILayout.Slider("From", tw.from, 0f, 1f);
var to = EditorGUILayout.Slider("To", tw.to, 0f, 1f);
var ds = tw.autoCleanup;
var pn = tw.colorProperty;
if (tw.GetComponent<MeshRenderer>() != null)
{
ds = EditorGUILayout.Toggle("Auto-cleanup", tw.autoCleanup);
pn = EditorGUILayout.TextField("Color Property", tw.colorProperty);
}
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
tw.autoCleanup = ds;
tw.colorProperty = pn;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 6ca1a2b070be6f04f9dc2b6756d084ff
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,30 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenColor))]
public class TweenColorEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenColor tw = target as TweenColor;
GUI.changed = false;
Color from = EditorGUILayout.ColorField("From", tw.from);
Color to = EditorGUILayout.ColorField("To", tw.to);
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7928b5af346eed04ba391047b8b0ddc8
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,30 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenFOV))]
public class TweenFOVEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenFOV tw = target as TweenFOV;
GUI.changed = false;
float from = EditorGUILayout.Slider("From", tw.from, 1f, 180f);
float to = EditorGUILayout.Slider("To", tw.to, 1f, 180f);
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 11db62d6da2a5f34590f41ebb958bd94
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,46 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenHeight))]
public class TweenHeightEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenHeight tw = target as TweenHeight;
GUI.changed = false;
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginDisabledGroup(tw.fromTarget != null);
var from = EditorGUILayout.FloatField("From", tw.from);
EditorGUI.EndDisabledGroup();
var fc = (RectTransform)EditorGUILayout.ObjectField(tw.fromTarget, typeof(RectTransform), true, GUILayout.Width(110f));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginDisabledGroup(tw.toTarget != null);
var to = EditorGUILayout.FloatField("To", tw.to);
EditorGUI.EndDisabledGroup();
var tc = (RectTransform)EditorGUILayout.ObjectField(tw.toTarget, typeof(RectTransform), true, GUILayout.Width(110f));
EditorGUILayout.EndHorizontal();
if (from < 0) from = 0;
if (to < 0) to = 0;
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
tw.fromTarget = fc;
tw.toTarget = tc;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4c135e5506eb921409b47fa6543134ec
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,33 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenOrthoSize))]
public class TweenOrthoSizeEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenOrthoSize tw = target as TweenOrthoSize;
GUI.changed = false;
float from = EditorGUILayout.FloatField("From", tw.from);
float to = EditorGUILayout.FloatField("To", tw.to);
if (from < 0f) from = 0f;
if (to < 0f) to = 0f;
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 37cda4ddb333a6d469473d36a439d20e
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,30 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenPosition))]
public class TweenPositionEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenPosition tw = target as TweenPosition;
GUI.changed = false;
Vector3 from = EditorGUILayout.Vector3Field("From", tw.from);
Vector3 to = EditorGUILayout.Vector3Field("To", tw.to);
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5c3ed7d7dc3fe434d8fbe43ba848c7de
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,32 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenRotation))]
public class TweenRotationEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenRotation tw = target as TweenRotation;
GUI.changed = false;
Vector3 from = EditorGUILayout.Vector3Field("From", tw.from);
Vector3 to = EditorGUILayout.Vector3Field("To", tw.to);
var quat = EditorGUILayout.Toggle("Quaternion", tw.quaternionLerp);
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
tw.quaternionLerp = quat;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 37920e4b9f98bd44fa1250a9d995475c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,30 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenScale))]
public class TweenScaleEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenScale tw = target as TweenScale;
GUI.changed = false;
Vector3 from = EditorGUILayout.Vector3Field("From", tw.from);
Vector3 to = EditorGUILayout.Vector3Field("To", tw.to);
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 50b7b0504ae552a42b20841c085dc185
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,9 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenTransform))]
public class TweenTransformEditor : UITweenerEditor
{
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 9ff6713338f44844c82de82685521dd3
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,30 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenVolume))]
public class TweenVolumeEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenVolume tw = target as TweenVolume;
GUI.changed = false;
float from = EditorGUILayout.Slider("From", tw.from, 0f, 1f);
float to = EditorGUILayout.Slider("To", tw.to, 0f, 1f);
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 023e6404a70e48148b315cf9737211af
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,46 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenWidth))]
public class TweenWidthEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 120f;
TweenWidth tw = target as TweenWidth;
GUI.changed = false;
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginDisabledGroup(tw.fromTarget != null);
var from = EditorGUILayout.FloatField("From", tw.from);
EditorGUI.EndDisabledGroup();
var fc = (RectTransform)EditorGUILayout.ObjectField(tw.fromTarget, typeof(RectTransform), true, GUILayout.Width(110f));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginDisabledGroup(tw.toTarget != null);
var to = EditorGUILayout.FloatField("To", tw.to);
EditorGUI.EndDisabledGroup();
var tc = (RectTransform)EditorGUILayout.ObjectField(tw.toTarget, typeof(RectTransform), true, GUILayout.Width(110f));
EditorGUILayout.EndHorizontal();
if (from < 0) from = 0;
if (to < 0) to = 0;
if (GUI.changed)
{
//NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
tw.fromTarget = fc;
tw.toTarget = tc;
//NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: d35cd8e39586acb4a842a0c77019d598
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,118 @@
#if UNITY_EDITOR
//-------------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2020 Tasharen Entertainment Inc
//-------------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(UITweener), true)]
public class UITweenerEditor : Editor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
EditorGUIUtility.labelWidth = 110f;
base.OnInspectorGUI();
DrawCommonProperties();
}
static public bool DrawHeader(string text, string key, bool forceOn, bool minimalistic)
{
bool state = EditorPrefs.GetBool(key, true);
if (!minimalistic) GUILayout.Space(3f);
if (!forceOn && !state) GUI.backgroundColor = new Color(0.8f, 0.8f, 0.8f);
GUILayout.BeginHorizontal();
GUI.changed = false;
if (minimalistic)
{
if (state) text = "\u25BC" + (char)0x200a + text;
else text = "\u25BA" + (char)0x200a + text;
GUILayout.BeginHorizontal();
GUI.contentColor = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.7f) : new Color(0f, 0f, 0f, 0.7f);
if (!GUILayout.Toggle(true, text, "PreToolbar2", GUILayout.MinWidth(20f))) state = !state;
GUI.contentColor = Color.white;
GUILayout.EndHorizontal();
}
else
{
text = "<b><size=11>" + text + "</size></b>";
if (state) text = "\u25BC " + text;
else text = "\u25BA " + text;
if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) state = !state;
}
if (GUI.changed) EditorPrefs.SetBool(key, state);
if (!minimalistic) GUILayout.Space(2f);
GUILayout.EndHorizontal();
GUI.backgroundColor = Color.white;
if (!forceOn && !state) GUILayout.Space(3f);
return state;
}
static public void BeginContents()
{
EditorGUILayout.BeginHorizontal(GUILayout.MinHeight(10f));
GUILayout.Space(10f);
GUILayout.BeginVertical();
GUILayout.Space(2f);
}
static public void EndContents()
{
GUILayout.Space(3f);
GUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
GUILayout.Space(3f);
}
protected void DrawCommonProperties ()
{
UITweener tw = target as UITweener;
if (DrawHeader("Tweener", "Tweener", false , true))
{
BeginContents();
EditorGUIUtility.labelWidth = 110f;
GUI.changed = false;
UITweener.Style style = (UITweener.Style)EditorGUILayout.EnumPopup("Play Style", tw.style);
AnimationCurve curve = EditorGUILayout.CurveField("Animation Curve", tw.animationCurve, GUILayout.Width(170f), GUILayout.Height(62f));
GUILayout.BeginHorizontal();
float dur = EditorGUILayout.FloatField("Duration", tw.duration, GUILayout.Width(170f));
GUILayout.Label("seconds");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
float del = EditorGUILayout.FloatField("Start Delay", tw.delay, GUILayout.Width(170f));
GUILayout.Label("seconds");
GUILayout.EndHorizontal();
var deff = (UITweener.DelayAffects)EditorGUILayout.EnumPopup("Delay Affects", tw.delayAffects);
int tg = EditorGUILayout.IntField("Tween Group", tw.tweenGroup, GUILayout.Width(170f));
bool ts = EditorGUILayout.Toggle("Ignore TimeScale", tw.ignoreTimeScale);
bool fx = EditorGUILayout.Toggle("Use Fixed Update", tw.useFixedUpdate);
if (GUI.changed)
{
tw.animationCurve = curve;
tw.style = style;
tw.ignoreTimeScale = ts;
tw.tweenGroup = tg;
tw.duration = dur;
tw.delay = del;
tw.delayAffects = deff;
tw.useFixedUpdate = fx;
}
EndContents();
}
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 3564c93409a4aaa44a48de1e49be56ba
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 391048bfcbd4480ebaf66c91987b291f
timeCreated: 1758179210
@@ -0,0 +1,252 @@
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
namespace SkierFramework
{
public class ControlItemDrawer
{
private UIControlDataEditor _container;
private CtrlItemData _itemData;
private bool _foldout = true;
private int _controlTypeIdx = 0;
public ControlItemDrawer(UIControlDataEditor container, CtrlItemData item)
{
_container = container;
_itemData = item;
}
public bool Draw()
{
EditorGUI.BeginChangeCheck();
Rect rect = EditorGUILayout.BeginVertical();
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("变量名 ", UIControlDataEditor.skin.label, GUILayout.Width(60f));
string newName = EditorGUILayout.TextField(_itemData.name, UIControlDataEditor.skin.textField).Trim();
if (newName != _itemData.name)
{
_itemData.name = newName;
(_container.target as UIControlData).SetDirty();
}
EditorGUILayout.Space();
_foldout = EditorGUILayout.Foldout(_foldout, _foldout ? "收起" : "展开", true);
if (GUILayout.Button("+", EditorStyles.miniButton))
{
_container.AddControlAfter(this);
return false;
}
if (GUILayout.Button("-", EditorStyles.miniButton))
{
_container.RemoveControl(this);
return false;
}
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
// 控件列表
if (_foldout)
{
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("变量类型 ", UIControlDataEditor.skin.label, GUILayout.Width(60f));
if (_controlTypeIdx == 0 && !string.IsNullOrEmpty(_itemData.type))
_controlTypeIdx = FindTypeIdx(_itemData.type);
if (EditorGUI.EndChangeCheck())
{
(_container.target as UIControlData).SetDirty();
}
EditorGUI.BeginChangeCheck();
_controlTypeIdx = EditorGUILayout.Popup(_controlTypeIdx, _container.allTypeNames, UIControlDataEditor.popupAlignLeft);
if (EditorGUI.EndChangeCheck())
{
if(_controlTypeIdx != 0)
{
if (!ChangeControlsTypeTo(_controlTypeIdx))
_controlTypeIdx = 0; // 切换失败,重置回自动
}
else // 被主动设置为了自动
_itemData.type = string.Empty;
(_container.target as UIControlData).SetDirty();
return false;
}
EditorGUI.BeginChangeCheck();
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
for (int i = 0, imax = _itemData.targets.Length; i < imax; i++)
{
Object obj = _itemData.targets[i];
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
_itemData.targets[i] = EditorGUILayout.ObjectField(obj, typeof(Object), true);
if (EditorGUI.EndChangeCheck())
{
(_container.target as UIControlData).SetDirty();
}
EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.Space();
if (GUILayout.Button("+", EditorStyles.miniButton))
{
InsertItem(i + 1);
return false;
}
if (GUILayout.Button("-", EditorStyles.miniButton))
{
if(_itemData.targets.Length == 1)
{
Debug.LogError("至少应保留一个控件");
return false;
}
else
{
RemoveItem(i);
return false;
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
}
}
EditorGUILayout.EndVertical();
if (EditorGUIUtility.isProSkin)
GUI.Box(new Rect(rect.x - 10f, rect.y - 5f, rect.width + 20f, rect.height + 15f), "");
else
GUI.Box(new Rect(rect.x - 10f, rect.y - 5f, rect.width + 20f, rect.height + 15f), "", UIControlDataEditor.skin.box);
if (EditorGUI.EndChangeCheck())
{
(_container.target as UIControlData).SetDirty();
}
PostProcess();
return true;
}
private void PostProcess()
{
// 默认将新添加的第一个控件的名字作为变量名
if (_itemData.targets.Length > 0 && _itemData.targets[0] != null && string.IsNullOrEmpty(_itemData.name))
_itemData.name = _itemData.targets[0].name.Trim();
}
private int FindTypeIdx(string typeName)
{
string[] allTypeNames = _container.allTypeNames;
for (int i = 0, imax = allTypeNames.Length; i < imax; i++)
{
if(allTypeNames[i] == typeName)
return i;
}
return 0;
}
private void InsertItem(int idx)
{
Object[] newArr = new Object[_itemData.targets.Length + 1];
for(int i = 0; i < idx; i++)
{
newArr[i] = _itemData.targets[i];
}
newArr[idx] = null;
for(int i = idx + 1; i < newArr.Length; i++)
{
newArr[i] = _itemData.targets[i - 1];
}
_itemData.targets = newArr;
}
private void RemoveItem(int idx)
{
Object[] newArr = new Object[_itemData.targets.Length - 1];
for(int i = 0; i < idx; i++)
{
newArr[i] = _itemData.targets[i];
}
for(int i = idx; i < newArr.Length; i++)
{
newArr[idx] = _itemData.targets[i + 1];
}
_itemData.targets = newArr;
}
/// <summary>
/// 将控件切换到指定类型
/// </summary>
/// <param name="typeIdx"></param>
private bool ChangeControlsTypeTo(int typeIdx)
{
System.Type targetType = _container.allTypes[typeIdx];
string targetTypeName = _container.allTypeNames[typeIdx];
bool isGameObject = targetType == typeof(GameObject);
for(int i = 0, imax = _itemData.targets.Length; i < imax; i++)
{
Object obj = _itemData.targets[i];
if (obj == null)
{
Debug.LogErrorFormat("[{0}.{1}] control[{2}] is null"
, _container.target.name, _itemData.name, i);
return false;
}
if(obj.GetType() != typeof(GameObject))
{
if((obj as Component) == null)
{
Debug.LogErrorFormat("[{0}.{1}] control[{2}] [{3}] must be GameObject or a Component"
, _container.target.name, _itemData.name, i, obj.name);
return false;
}
obj = (obj as Component).gameObject;
}
GameObject go = obj as GameObject;
if (isGameObject)
_itemData.targets[i] = go;
else
{
Component comp = go.GetComponent(targetType);
if(comp == null)
{
Debug.LogErrorFormat("[{0}.{1}] control[{2}] [{3}] isn't a {4}"
, _container.target.name, _itemData.name, i, go.name, targetTypeName);
return false;
}
_itemData.targets[i] = comp;
}
}
_itemData.type = targetTypeName;
return true;
}
}
}
#endif
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 5a19fd525bc43e2439c14dac7ed67295
timeCreated: 1521794417
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,73 @@
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace SkierFramework
{
public class SubUIItemDrawer
{
private UIControlDataEditor _container;
private SubUIItemData _itemData;
private bool _foldout = true;
public SubUIItemDrawer(UIControlDataEditor container, SubUIItemData itemData)
{
_container = container;
_itemData = itemData;
}
public bool Draw()
{
Rect rect = EditorGUILayout.BeginVertical();
{
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("子UI名 ", UIControlDataEditor.skin.label);
_itemData.name = EditorGUILayout.TextField(_itemData.name, UIControlDataEditor.skin.textField).Trim();
EditorGUILayout.Space();
_foldout = EditorGUILayout.Foldout(_foldout, _foldout ? "收起" : "展开", true);
if (GUILayout.Button("+", EditorStyles.miniButton))
{
_container.AddSubUIAfter(this);
return false;
}
if (GUILayout.Button("-", EditorStyles.miniButton))
{
_container.RemoveSubUI(this);
return false;
}
}
EditorGUILayout.EndHorizontal();
if (_foldout)
{
EditorGUILayout.Space();
_itemData.subUIData = EditorGUILayout.ObjectField(_itemData.subUIData as Object, typeof(UIControlData), true) as UIControlData;
}
}
EditorGUILayout.EndVertical();
if (EditorGUIUtility.isProSkin)
GUI.Box(new Rect(rect.x - 10f, rect.y - 5f, rect.width + 20f, rect.height + 15f), "");
else
GUI.Box(new Rect(rect.x - 10f, rect.y - 5f, rect.width + 20f, rect.height + 15f), "", UIControlDataEditor.skin.box);
PostProcess();
return true;
}
private void PostProcess()
{
// 默认将控件的名字作为变量名
if (_itemData.subUIData != null && string.IsNullOrEmpty(_itemData.name))
_itemData.name = _itemData.subUIData.name.Trim();
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2db1a302384342148abb76d0508f2944
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,234 @@
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
namespace SkierFramework
{
[CustomEditor(typeof(UIControlData))]
public class UIControlDataEditor : Editor
{
public static GUISkin skin;
public static GUIStyle popupAlignLeft; // TODO 挪出去一个 SkinManager
public string[] allTypeNames;
public Type[] allTypes;
private List<CtrlItemData> _ctrlItemDatas;
private List<SubUIItemData> _subUIItemDatas;
private List<ControlItemDrawer> _ctrlItemDrawers;
private List<SubUIItemDrawer> _subUIItemDrawers;
void Awake()
{
if(skin == null)
{
if (EditorGUIUtility.isProSkin)
skin = Resources.Load("Editor/UIControlDataSkinPro") as GUISkin;
else
skin = Resources.Load("Editor/UIControlDataSkinPersonal") as GUISkin;
}
if(popupAlignLeft == null)
{
popupAlignLeft = new GUIStyle("Popup");
popupAlignLeft.alignment = TextAnchor.MiddleLeft;
}
allTypeNames = UIControlData.GetAllTypeNames();
allTypes = UIControlData.GetAllTypes();
UIControlData uIControlData = target as UIControlData;
if (uIControlData != null)
{
uIControlData.CorrectComponents();
uIControlData.CheckSubUIs();
}
}
public override void OnInspectorGUI()
{
if (skin == null || skin.customStyles == null || skin.customStyles.Length == 0)
{
base.OnInspectorGUI();
return;
}
UIControlData data = target as UIControlData;
if(data.ctrlItemDatas == null)
data.ctrlItemDatas = new List<CtrlItemData>();
if(data.subUIItemDatas == null)
data.subUIItemDatas = new List<SubUIItemData>();
_ctrlItemDatas = data.ctrlItemDatas;
_subUIItemDatas = data.subUIItemDatas;
CheckDrawers();
EditorGUILayout.BeginVertical();
EditorGUILayout.Space();
// 绘制控件绑定
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("控件绑定", skin.customStyles[0]);
if(_ctrlItemDrawers.Count == 0)
{
if(GUILayout.Button("+", EditorStyles.miniButton))
{
AddControlAfter(-1);
Repaint();
return;
}
}
EditorGUILayout.EndHorizontal();
foreach (var drawer in _ctrlItemDrawers)
{
GUILayout.Space(10f);
if (!drawer.Draw())
{
Repaint();
return;
}
GUILayout.Space(10f);
}
GUILayout.Space(10f);
// 绘制子UI
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("子UI绑定", skin.customStyles[0]);
if(_subUIItemDrawers.Count == 0)
{
if (GUILayout.Button("+", EditorStyles.miniButton))
{
AddSubUIAfter(-1);
Repaint();
return;
}
}
EditorGUILayout.EndHorizontal();
foreach(var drawer in _subUIItemDrawers)
{
GUILayout.Space(10f);
if (!drawer.Draw())
{
Repaint();
return;
}
GUILayout.Space(10f);
}
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUILayout.EndVertical();
this.Repaint();
}
public void AddControlAfter(ControlItemDrawer drawer)
{
int idx = _ctrlItemDrawers.IndexOf(drawer);
Debug.Assert(idx != -1);
AddControlAfter(idx);
}
public void AddSubUIAfter(SubUIItemDrawer drawer)
{
int idx = _subUIItemDrawers.IndexOf(drawer);
Debug.Assert(idx != -1);
AddSubUIAfter(idx);
}
public void RemoveControl(ControlItemDrawer drawer)
{
int idx = _ctrlItemDrawers.IndexOf(drawer);
Debug.Assert(idx != -1);
RemoveControl(idx);
}
public void RemoveSubUI(SubUIItemDrawer drawer)
{
int idx = _subUIItemDrawers.IndexOf(drawer);
Debug.Assert(idx != -1);
RemoveSubUI(idx);
}
#region Private
private void CheckDrawers()
{
if (_ctrlItemDrawers == null)
{
_ctrlItemDrawers = new List<ControlItemDrawer>(100);
foreach(var item in _ctrlItemDatas)
{
ControlItemDrawer drawer = new ControlItemDrawer(this, item);
_ctrlItemDrawers.Add(drawer);
}
}
if(_subUIItemDrawers == null)
{
_subUIItemDrawers = new List<SubUIItemDrawer>(100);
foreach(var item in _subUIItemDatas)
{
SubUIItemDrawer drawer = new SubUIItemDrawer(this, item);
_subUIItemDrawers.Add(drawer);
}
}
}
private void AddControlAfter(int idx)
{
CtrlItemData itemData = new CtrlItemData();
_ctrlItemDatas.Insert(idx + 1, itemData);
ControlItemDrawer drawer = new ControlItemDrawer(this, itemData);
_ctrlItemDrawers.Insert(idx + 1, drawer);
SetPrefabDirty();
}
private void AddSubUIAfter(int idx)
{
SubUIItemData itemData = new SubUIItemData();
_subUIItemDatas.Insert(idx + 1, itemData);
SubUIItemDrawer drawer = new SubUIItemDrawer(this, itemData);
_subUIItemDrawers.Insert(idx + 1, drawer);
SetPrefabDirty();
}
private void RemoveControl(int idx)
{
_ctrlItemDatas.RemoveAt(idx);
_ctrlItemDrawers.RemoveAt(idx);
SetPrefabDirty();
}
private void RemoveSubUI(int idx)
{
_subUIItemDatas.RemoveAt(idx);
_subUIItemDrawers.RemoveAt(idx);
SetPrefabDirty();
}
private void SetPrefabDirty()
{
UIControlData uIControlData = target as UIControlData;
uIControlData.SetDirty();
}
#endregion
}
}
#endif
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 27c41d595322d554a9afea0d2b516863
timeCreated: 1521786373
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,564 @@
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Text.RegularExpressions;
using System.IO;
using SkierFramework;
using System;
using System.Linq;
using Newtonsoft.Json;
using YooAsset.Editor;
public class UICreateWindow : EditorWindow
{
#region MenuItem
[MenuItem("Assets/Create/CreateUI")]
private static void CopyUI()
{
if (Selection.activeObject == null || !(Selection.activeObject is GameObject))
{
Debug.LogError("请选择UI预制体!");
return;
}
UICreateWindow.OpenWindow().uiPrefab = Selection.activeObject as GameObject;
}
[MenuItem("Tools/UI管理")]
public static UICreateWindow OpenWindow()
{
var window = GetWindow<UICreateWindow>("UI管理");
if (window == null)
{
window = CreateWindow<UICreateWindow>("UI管理");
}
window.name = "UI管理";
window.Focus();
return window;
}
#endregion
private string _packageName;
private string _mInput;
private Vector2 _scroll;
private Vector2 _scroll2;
private Vector2 _scroll3;
private string _uiViewTemplate = "UIViewTemplate";
private string _uiConfig = "UIConfig";
private string _uiType = "UIType";
private string _saveUIPath = "SaveUIPath";
private string _uiName;
public GameObject uiPrefab;
private Dictionary<string, string> _uiNames = new Dictionary<string, string>();
private Dictionary<string, UIConfigJson> _uiJsonDatas = new Dictionary<string, UIConfigJson>();
private bool _isWindow = true;
private UILayer _layer = UILayer.NormalLayer;
private IEnumerable<Type> uiViews;
private void OnEnable()
{
TryGetPath(ref _uiViewTemplate, _uiViewTemplate, ".txt");
TryGetPath(ref _uiType, _uiType, ".cs");
TryGetPath(ref _uiConfig, _uiConfig, ".json");
_saveUIPath = PlayerPrefs.GetString(_saveUIPath, "Assets/Scripts");
_uiJsonDatas.Clear();
_uiNames.Clear();
// string[] strs = Enum.GetNames(typeof(UIType));
uiViews = ReflectionHelper.GetAllUIViewTypes();
foreach (var uiView in uiViews)
{
string str = uiView.Name;
if (str.Equals("Max")) continue;
var jsonData = GetUIJson(str);
if (jsonData == null || string.IsNullOrEmpty(jsonData.path)) continue;
var scriptPath = GetUIScript(str, true);
_uiNames.AddOrUpdate(str, scriptPath);
}
}
private void OnGUI()
{
EditorGUILayout.LabelField("通过[Tools/UI管理]可以打开");
_scroll = EditorGUILayout.BeginScrollView(_scroll);
{
EditorGUILayout.HelpBox("UI基础文件", MessageType.Info);
{
_packageName = StringInputFild("PackageName", "UIPackageName");
PathField("UI模板文件.txt", ref _uiViewTemplate, nameof(_uiViewTemplate), ".txt");
PathField("UI配置文件.json", ref _uiConfig, nameof(_uiConfig), ".json");
PathField("UIType.cs", ref _uiType, nameof(_uiType), ".cs");
}
EditorGUILayout.Space(10);
EditorGUILayout.BeginHorizontal();
{
_scroll2 = EditorGUILayout.BeginScrollView(_scroll2, "box", GUILayout.Width(position.width * 0.4f - 6));
{
EditorGUILayout.HelpBox("已创建的UI", MessageType.Info);
_mInput = EditorGUILayout.TextField(_mInput, EditorStyles.toolbarSearchField, GUILayout.Height(20));
//string[] strs = Enum.GetNames(typeof(UIType));
foreach (var uiView in uiViews)
{
string str = uiView.Name;
if (str.Equals("Max")) continue;
if (!string.IsNullOrEmpty(_mInput) && !str.Contains(_mInput)) continue;
var jsonData = GetUIJson(str);
var scriptPath = GetUIScript(str);
if (jsonData == null || string.IsNullOrEmpty(jsonData.path) ||
string.IsNullOrEmpty(scriptPath)) continue;
var defaultColor = GUI.color;
if (str.Equals(_uiName))
{
GUI.color = Color.yellow;
}
EditorGUILayout.BeginHorizontal("box");
if (GUILayout.Button("选中"))
{
uiPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(jsonData.path);
}
EditorGUILayout.ObjectField(AssetDatabase.LoadAssetAtPath<GameObject>(jsonData.path),
typeof(GameObject), true);
EditorGUILayout.ObjectField(AssetDatabase.LoadAssetAtPath<TextAsset>(scriptPath),
typeof(TextAsset), true);
EditorGUILayout.EndHorizontal();
GUI.color = defaultColor;
}
if (GUILayout.Button("标记资源"))
{
Mask();
}
}
EditorGUILayout.EndScrollView();
_scroll3 = EditorGUILayout.BeginScrollView(_scroll3, "box", GUILayout.Width(position.width * 0.6f - 6));
{
EditorGUILayout.HelpBox("UI操作", MessageType.Info);
uiPrefab = EditorGUILayout.ObjectField("UI预制体", uiPrefab, typeof(GameObject), true) as GameObject;
if (uiPrefab != null)
{
_uiName = uiPrefab.name;
var uiScriptPath = GetUIScript(_uiName);
if (string.IsNullOrEmpty(uiScriptPath))
{
if (GUILayout.Button($"选择创建路径:{_saveUIPath}"))
{
var newPath = EditorUtility.OpenFolderPanel("UI生成路径", _saveUIPath, "");
_saveUIPath = newPath.Replace(Application.dataPath, "Assets");
PlayerPrefs.SetString(nameof(_saveUIPath), _saveUIPath);
}
if (uiPrefab != null)
{
EditorGUILayout.TextField("UI生成路径", $"{_saveUIPath}/{_uiName}.cs");
}
_isWindow = EditorGUILayout.Toggle("是否为窗口", _isWindow);
_layer = (UILayer)EditorGUILayout.EnumPopup("UILayer设置", _layer);
var defaultColor = GUI.color;
GUI.color = Color.green;
if (GUILayout.Button("创建UI"))
{
// 生成代码
string str = Regex.Replace(File.ReadAllText(_uiViewTemplate), "UIXXXView", _uiName);
UIControlData uiControlData = uiPrefab.GetComponent<UIControlData>();
if (uiControlData != null)
{
uiControlData.CopyCodeToClipBoardPrivate();
}
str = Regex.Replace(str, "//UIControlData",
uiControlData != null ? UnityEngine.GUIUtility.systemCopyBuffer : "");
string newPath = $"{_saveUIPath}/{_uiName}.cs";
File.WriteAllText(newPath, str);
var jsonData = new UIConfigJson
{
uiType = _uiName,
path = AssetDatabase.GetAssetPath(uiPrefab),
isWindow = _isWindow,
uiLayer = _layer.ToString(),
};
_uiJsonDatas.Add(_uiName, jsonData);
_uiNames.Add(_uiName, newPath);
SaveJson();
// 生成UIType
var newStr = Regex.Replace(File.ReadAllText(_uiType), "Max,", $"{_uiName},\n\t\tMax,");
File.Delete(_uiType);
File.WriteAllText(_uiType, newStr);
Debug.Log("生成成功:" + newPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
GUI.color = defaultColor;
}
else
{
var jsonData = GetUIJson(_uiName);
if (UnityEditor.PrefabUtility.IsPartOfPrefabAsset(uiPrefab))
{
// 预制体资源就是自身
jsonData.path = UnityEditor.AssetDatabase.GetAssetPath(uiPrefab);
}
EditorGUILayout.ObjectField("已创建脚本",
AssetDatabase.LoadAssetAtPath(uiScriptPath, typeof(TextAsset)), typeof(TextAsset),
true);
jsonData.isWindow = EditorGUILayout.Toggle("是否为窗口", jsonData.isWindow);
Enum.TryParse(jsonData.uiLayer, out UILayer layer);
jsonData.uiLayer = EditorGUILayout.EnumPopup("UILayer设置", layer).ToString();
var defaultColor = GUI.color;
GUI.color = Color.green;
if (GUILayout.Button("保存设置"))
{
SaveJson();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
GUI.color = defaultColor;
GUI.color = Color.red;
if (GUILayout.Button("删除UI脚本"))
{
if (EditorUtility.DisplayDialog("是否确认删除",
$"请确认是否删除:\n{uiScriptPath}\n同时会清除JsonUIType中相关数据", "确定", "取消"))
{
// 清除UIType中指定类型
var uiTypeStr = File.ReadAllText(_uiType);
int index = uiTypeStr.IndexOf(_uiName);
int leftIndex = uiTypeStr.Substring(0, index).LastIndexOf(',') + 1;
int rightIndex = uiTypeStr.Substring(index, uiTypeStr.Length - index).IndexOf(',') +
index + 1;
var newStr = uiTypeStr.Substring(0, leftIndex) +
uiTypeStr.Substring(rightIndex, uiTypeStr.Length - rightIndex);
File.Delete(_uiType);
File.WriteAllText(_uiType, newStr);
// 清除UIConfig中的指定类型
_uiJsonDatas.Remove(_uiName);
_uiNames.Remove(_uiName);
SaveJson();
// 删除文件
File.Delete(uiScriptPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
_uiNames.Remove(_uiName);
}
}
GUI.color = defaultColor;
}
}
else
{
_uiName = "";
}
}
EditorGUILayout.EndScrollView();
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
}
private void SaveJson()
{
List<UIConfigJson> list = new List<UIConfigJson>();
foreach (var name in _uiNames.Keys)
{
if (_uiJsonDatas.TryGetValue(name, out var data))
{
list.Add(data);
}
}
File.Delete(_uiConfig);
File.WriteAllText(_uiConfig, JsonConvert.SerializeObject(list, Formatting.Indented));
}
private void TryGetPath(ref string path, string pathName, string endsWith)
{
path = PlayerPrefs.GetString(pathName);
if (!File.Exists(path))
{
string[] ids = AssetDatabase.FindAssets(pathName);
if (ids != null)
{
foreach (var id in ids)
{
var str = AssetDatabase.GUIDToAssetPath(id);
if (str.EndsWith(endsWith))
{
path = str;
}
}
}
}
}
private string GetUIScript(string name, bool tryFind = false)
{
if (_uiNames.TryGetValue(name, out string path))
{
return path;
}
if (!tryFind)
{
return string.Empty;
}
if (GetUIJson(name) == null) return string.Empty;
string[] ids = AssetDatabase.FindAssets(name);
if (ids != null)
{
foreach (var id in ids)
{
var str = AssetDatabase.GUIDToAssetPath(id);
if (str.EndsWith(".cs"))
{
return str;
}
}
}
return string.Empty;
}
private UIConfigJson GetUIJson(string name)
{
if (_uiJsonDatas.Count == 0)
{
try
{
var json = File.ReadAllText(_uiConfig);
var list = JsonConvert.DeserializeObject<List<UIConfigJson>>(json);
foreach (var item in list)
{
_uiJsonDatas.AddOrUpdate(item.uiType, item);
}
}
catch (Exception e)
{
Debug.LogError(e);
}
}
if (_uiJsonDatas.TryGetValue(name, out var jsonData))
{
return jsonData;
}
return null;
}
private string StringInputFild(string name, string endsWith)
{
string value = PlayerPrefs.GetString(name);
if (string.IsNullOrEmpty(value))
{
if (!string.IsNullOrEmpty(endsWith))
{
PlayerPrefs.SetString(name, endsWith);
}
}
else
{
endsWith = value;
}
return EditorGUILayout.TextField(name, endsWith);
}
private void PathField(string name, ref string path, string pathName, string endsWith)
{
var obj = EditorGUILayout.ObjectField(name, AssetDatabase.LoadAssetAtPath(path, typeof(TextAsset)),
typeof(TextAsset), true);
if (obj != null)
{
var newPath = AssetDatabase.GetAssetPath(obj);
if (newPath.EndsWith(endsWith) && !newPath.Equals(path))
{
path = newPath;
PlayerPrefs.SetString(pathName, path);
}
}
}
#region Mask
public void Mask()
{
// //清空主包旧数据
AssetBundleCollectorPackage assetBundleCollectorPackage = null;
foreach (var package in AssetBundleCollectorSettingData.Setting.Packages)
{
if (package.PackageName == _packageName)
{
assetBundleCollectorPackage = package;
}
}
if (assetBundleCollectorPackage == null)
{
var setting = YooAsset.Editor.AssetBundleCollectorSettingData.Setting;
setting.ShowPackageView = true;
setting.UniqueBundleName = true;
//创建Package文件
assetBundleCollectorPackage = YooAsset.Editor.AssetBundleCollectorSettingData.CreatePackage(_packageName);
}
//检测Packages是否存在TestPackage
assetBundleCollectorPackage.PackageName = _packageName;
assetBundleCollectorPackage.EnableAddressable = false;
assetBundleCollectorPackage.IncludeAssetGUID = true;
assetBundleCollectorPackage.AutoCollectShaders = true;
assetBundleCollectorPackage.IgnoreRuleName = "NormalIgnoreRule";
//标记json配置文件
if (!string.IsNullOrEmpty(_uiConfig))
{
var collectorGroup = ReflectionHelper.RemoveGroup(assetBundleCollectorPackage, "Config");
var guid = ReflectionHelper.GetGUIDByRelativePath(_uiConfig);
AssetBundleCollector collector = new AssetBundleCollector()
{
CollectPath = _uiConfig,
CollectorGUID = guid,
CollectorType = ECollectorType.MainAssetCollector,
AddressRuleName = nameof(AddressByFolderAndFileName),
};
YooAsset.Editor.AssetBundleCollectorSettingData.CreateCollector(collectorGroup, collector);
}
//标记预制体
foreach (var data in _uiJsonDatas)
{
var collectorGroup = ReflectionHelper.RemoveGroup(assetBundleCollectorPackage, "Prefab");
var guid = ReflectionHelper.GetGUIDByRelativePath(data.Value.path);
AssetBundleCollector collector = new AssetBundleCollector()
{
CollectPath = data.Value.path,
CollectorGUID = guid,
CollectorType = ECollectorType.MainAssetCollector,
AddressRuleName = nameof(AddressByFolderAndFileName),
AssetTags = data.Value.uiLayer.ToString(),
};
YooAsset.Editor.AssetBundleCollectorSettingData.CreateCollector(collectorGroup, collector);
}
YooAsset.Editor.AssetBundleCollectorSettingData.SaveFile();
Debug.Log("MarkAsset Successful");
}
#endregion
}
#endif
static class ReflectionHelper
{
public static IEnumerable<T> CreateAllInstancesOf<T>()
{
return typeof(ReflectionHelper).Assembly.GetTypes() //获取当前类库下所有类型
.Where(t => typeof(T).IsAssignableFrom(t)) //获取间接或直接继承t的所有类型
.Where(t => !t.IsAbstract && t.IsClass) //获取非抽象类 排除接口继承
.Select(t => (T)Activator.CreateInstance(t)); //创造实例,并返回结果(项目需求,可删除)
}
// 新增方法:专门用于查找UIView类型的所有实现类
public static IEnumerable<Type> GetAllUIViewTypes()
{
// 查找所有程序集中的UIView类型实现
var uiviewType = typeof(UIView);
List<Type> result = new List<Type>();
// 遍历所有已加载的程序集
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
result.AddRange(assembly.GetTypes()
.Where(t => uiviewType.IsAssignableFrom(t))
.Where(t => !t.IsAbstract && t.IsClass));
}
catch (Exception)
{
// 忽略无法访问的程序集
}
}
return result;
}
/// <summary>
/// 根据相对路径获取资源的GUID
/// </summary>
/// <param name="relativePath">相对于Assets目录的路径,例如:"Assets/UI/Prefabs/LoginPanel.prefab"</param>
/// <returns>资源的GUID字符串,如果路径无效则返回空字符串</returns>
public static string GetGUIDByRelativePath(string relativePath)
{
// 检查路径是否为空
if (string.IsNullOrEmpty(relativePath))
{
Debug.LogError("相对路径不能为空");
return string.Empty;
}
// 检查路径是否存在
if (!AssetDatabase.IsValidFolder(Path.GetDirectoryName(relativePath)) &&
!System.IO.File.Exists(Path.Combine(Application.dataPath, relativePath.Replace("Assets/", ""))))
{
Debug.LogError(string.Format("路径不存在: {0}", relativePath));
return string.Empty;
}
// 获取GUID
string guid = AssetDatabase.AssetPathToGUID(relativePath);
if (string.IsNullOrEmpty(guid))
{
Debug.LogWarning(string.Format("无法获取路径的GUID: {0}", relativePath));
}
return guid;
}
public static AssetBundleCollectorGroup RemoveGroup(AssetBundleCollectorPackage package, string groupName)
{
//删除的Group
var groupToDelete = package.Groups.FirstOrDefault(g => g.GroupName == groupName);
if (groupToDelete == null)
{
UnityEngine.Debug.LogError($"在Package中未找到Group '{groupName}'");
}
// 3. 从Package的Groups集合中删除该Group
package.Groups.Remove(groupToDelete);
return YooAsset.Editor.AssetBundleCollectorSettingData.CreateGroup(package, groupName);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 96a0d05f5869aed43bd7ab82a8bd430c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using TMPro;
namespace SkierFramework
{
public class UIXXXView : UIView
{
//UIControlData
public override void OnInit(UIControlData uIControlData, UIViewController controller)
{
base.OnInit(uIControlData, controller);
}
public override void OnOpen(object userData)
{
base.OnOpen(userData);
}
public override void OnAddListener()
{
base.OnAddListener();
}
public override void OnRemoveListener()
{
base.OnRemoveListener();
}
public override void OnClose()
{
base.OnClose();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ca37d3bfaabc8124cabb4b71f309b4c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 125226ccd07f47c5bf3b94157bf12fc3
timeCreated: 1758179120
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f6e218215da269c45b6b578b4eb0da12
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,268 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
namespace SkierFramework
{
public enum AnchorPresets
{
TopLeft,
TopCenter,
TopRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
BottomLeft,
BottonCenter,
BottomRight,
BottomStretch,
VertStretchLeft,
VertStretchRight,
VertStretchCenter,
HorStretchTop,
HorStretchMiddle,
HorStretchBottom,
StretchAll
}
public enum PivotPresets
{
TopLeft,
TopCenter,
TopRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
BottomLeft,
BottomCenter,
BottomRight,
}
public static class UIExtension
{
public static void SetAnchor(this RectTransform source, AnchorPresets allign, int offsetX = 0, int offsetY = 0)
{
source.anchoredPosition = new Vector3(offsetX, offsetY, 0);
switch (allign)
{
case (AnchorPresets.TopLeft):
{
source.anchorMin = new Vector2(0, 1);
source.anchorMax = new Vector2(0, 1);
break;
}
case (AnchorPresets.TopCenter):
{
source.anchorMin = new Vector2(0.5f, 1);
source.anchorMax = new Vector2(0.5f, 1);
break;
}
case (AnchorPresets.TopRight):
{
source.anchorMin = new Vector2(1, 1);
source.anchorMax = new Vector2(1, 1);
break;
}
case (AnchorPresets.MiddleLeft):
{
source.anchorMin = new Vector2(0, 0.5f);
source.anchorMax = new Vector2(0, 0.5f);
break;
}
case (AnchorPresets.MiddleCenter):
{
source.anchorMin = new Vector2(0.5f, 0.5f);
source.anchorMax = new Vector2(0.5f, 0.5f);
break;
}
case (AnchorPresets.MiddleRight):
{
source.anchorMin = new Vector2(1, 0.5f);
source.anchorMax = new Vector2(1, 0.5f);
break;
}
case (AnchorPresets.BottomLeft):
{
source.anchorMin = new Vector2(0, 0);
source.anchorMax = new Vector2(0, 0);
break;
}
case (AnchorPresets.BottonCenter):
{
source.anchorMin = new Vector2(0.5f, 0);
source.anchorMax = new Vector2(0.5f, 0);
break;
}
case (AnchorPresets.BottomRight):
{
source.anchorMin = new Vector2(1, 0);
source.anchorMax = new Vector2(1, 0);
break;
}
case (AnchorPresets.HorStretchTop):
{
source.anchorMin = new Vector2(0, 1);
source.anchorMax = new Vector2(1, 1);
break;
}
case (AnchorPresets.HorStretchMiddle):
{
source.anchorMin = new Vector2(0, 0.5f);
source.anchorMax = new Vector2(1, 0.5f);
break;
}
case (AnchorPresets.HorStretchBottom):
{
source.anchorMin = new Vector2(0, 0);
source.anchorMax = new Vector2(1, 0);
break;
}
case (AnchorPresets.VertStretchLeft):
{
source.anchorMin = new Vector2(0, 0);
source.anchorMax = new Vector2(0, 1);
break;
}
case (AnchorPresets.VertStretchCenter):
{
source.anchorMin = new Vector2(0.5f, 0);
source.anchorMax = new Vector2(0.5f, 1);
break;
}
case (AnchorPresets.VertStretchRight):
{
source.anchorMin = new Vector2(1, 0);
source.anchorMax = new Vector2(1, 1);
break;
}
case (AnchorPresets.StretchAll):
{
source.anchorMin = new Vector2(0, 0);
source.anchorMax = new Vector2(1, 1);
source.sizeDelta = Vector2.zero;
break;
}
}
}
public static void SetPivot(this RectTransform source, PivotPresets preset)
{
switch (preset)
{
case (PivotPresets.TopLeft):
{
source.pivot = new Vector2(0, 1);
break;
}
case (PivotPresets.TopCenter):
{
source.pivot = new Vector2(0.5f, 1);
break;
}
case (PivotPresets.TopRight):
{
source.pivot = new Vector2(1, 1);
break;
}
case (PivotPresets.MiddleLeft):
{
source.pivot = new Vector2(0, 0.5f);
break;
}
case (PivotPresets.MiddleCenter):
{
source.pivot = new Vector2(0.5f, 0.5f);
break;
}
case (PivotPresets.MiddleRight):
{
source.pivot = new Vector2(1, 0.5f);
break;
}
case (PivotPresets.BottomLeft):
{
source.pivot = new Vector2(0, 0);
break;
}
case (PivotPresets.BottomCenter):
{
source.pivot = new Vector2(0.5f, 0);
break;
}
case (PivotPresets.BottomRight):
{
source.pivot = new Vector2(1, 0);
break;
}
}
}
public static CanvasGroup CreateBlackMask(Transform parent, float alpha = 0, string name = null)
{
GameObject maskGo = new GameObject("Black Mask");
RectTransform rectTransform = maskGo.AddComponent<RectTransform>();
rectTransform.SetParentEx(parent);
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
Image image = maskGo.AddComponent<Image>();
image.color = Color.black;
image.raycastTarget = false;
CanvasGroup canvasGroup = maskGo.AddComponent<CanvasGroup>();
canvasGroup.alpha = alpha;
if(name != null)
canvasGroup.name = name;
return canvasGroup;
}
public static Canvas CreateLayerCanvas(UILayer layer, bool is3D, Transform parent, Camera camera, float width, float height)
{
GameObject canvasGo = new GameObject(layer.ToString());
RectTransform rectTransform = canvasGo.AddComponent<RectTransform>();
rectTransform.SetParentEx(parent);
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
canvasGo.layer = is3D ? Layer.Default : Layer.UI;
Canvas canvas = canvasGo.AddComponent<Canvas>();
canvas.renderMode = is3D ? RenderMode.WorldSpace : RenderMode.ScreenSpaceCamera;
canvas.overrideSorting = true;
canvas.sortingOrder = (int)layer;
canvas.worldCamera = camera;
canvas.pixelPerfect = false;
CanvasScaler canvasScaler = canvasGo.AddComponent<CanvasScaler>();
canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
canvasScaler.referenceResolution = new Vector2(height,width);
canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.Expand;
canvasGo.AddComponent<GraphicRaycaster>();
return canvas;
}
/// <summary>
/// 为方便统一处理点击音效等
/// </summary>
public static void AddClick(this Button button, UnityAction callback)
{
button.onClick.AddListener(callback);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b521dcf8e49760e4fa28db6a6436ebc3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ab9e1d815209d5e469824bfa1bbc399c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace SkierFramework
{
public static class Layer
{
public const int Default = 0;
public const int TransparentFX = 1;
public const int IgnoreRaycast = 2;
public const int Water = 4;
public const int UI = 5;
public const int UIRenderToTarget = 6;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f57fecb20b667bb45a6240fd6b16fc80
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace SkierFramework
{
public static class ObjectExtension
{
private static readonly List<Transform> s_CachedTransforms = new List<Transform>();
public static T GetOrAddComponent<T>(this Component obj) where T : Component
{
return obj.gameObject.GetOrAddComponent<T>();
}
public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
{
T t = gameObject.GetComponent<T>();
if (t == null)
t = gameObject.AddComponent<T>();
return t;
}
public static Component GetOrAddComponent(this Component obj, Type type)
{
return obj.gameObject.GetOrAddComponent(type);
}
public static Component GetOrAddComponent(this GameObject gameObject, Type type)
{
if (gameObject == null) return null;
Component component = gameObject.GetComponent(type);
if (component == null)
component = gameObject.AddComponent(type);
return component;
}
public static void SetParentEx(this Transform transform, Transform parent)
{
transform.SetParent(parent);
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
transform.localScale = Vector3.one;
}
public static void SetLayerRecursively(this GameObject gameObject, int layer)
{
gameObject.GetComponentsInChildren(true, s_CachedTransforms);
for (int i = 0; i < s_CachedTransforms.Count; i++)
{
s_CachedTransforms[i].gameObject.layer = layer;
}
s_CachedTransforms.Clear();
}
public static void AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue value)
{
if (dict.ContainsKey(key))
dict[key] = value;
else
dict.Add(key, value);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1255735e746b217478dc63262723567a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,194 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace SkierFramework
{
public static class Pool
{
public readonly static List<PoolBase> AllPool = new List<PoolBase>();
public static void ReleaseAll()
{
foreach (var pool in AllPool)
{
pool.Dispose();
}
AllPool.Clear();
}
}
public interface IObject
{
void OnRelease();
}
public interface PoolBase
{
void Dispose();
}
public class ObjectPool<T> : PoolBase where T : new()
{
private static ObjectPool<T> Instance;
private Stack<T> _pool;
private ObjectPool() { }
private static void Init()
{
if (Instance == null)
{
Instance = new ObjectPool<T>();
Instance._pool = new Stack<T>();
Pool.AllPool.Add(Instance);
}
}
public static T Get()
{
Init();
if (Instance._pool.Count > 0)
{
return Instance._pool.Pop();
}
else
{
return new T();
}
}
public static void Release(T obj)
{
if (obj == null || Instance == null) return;
if (obj is IObject interfac)
{
interfac.OnRelease();
}
Instance._pool.Push(obj);
}
public void Dispose()
{
if (Instance != null)
{
if (Instance._pool != null)
{
Instance._pool.Clear();
Instance._pool = null;
}
Instance = null;
}
}
}
public class ListPool<T> : PoolBase
{
private static ListPool<T> Instance;
private Stack<List<T>> _pool;
private ListPool() { }
private static void Init()
{
if (Instance == null)
{
Instance = new ListPool<T>();
Instance._pool = new Stack<List<T>>();
Pool.AllPool.Add(Instance);
}
}
public static List<T> Get()
{
Init();
if (Instance._pool.Count > 0)
{
return Instance._pool.Pop();
}
else
{
return new List<T>();
}
}
public static void Release(List<T> list)
{
if (list == null || Instance == null) return;
list.Clear();
Instance._pool.Push(list);
}
public void Dispose()
{
if (Instance != null)
{
if (Instance._pool != null)
{
Instance._pool.Clear();
Instance._pool = null;
}
Instance = null;
}
}
}
public class DictionaryPool<Key, Value> : PoolBase
{
private static DictionaryPool<Key, Value> Instance;
private Stack<Dictionary<Key, Value>> _pool;
private DictionaryPool() { }
private static void Init()
{
if (Instance == null)
{
Instance = new DictionaryPool<Key, Value>();
Instance._pool = new Stack<Dictionary<Key, Value>>();
Pool.AllPool.Add(Instance);
}
}
public static Dictionary<Key, Value> Get()
{
Init();
if (Instance._pool.Count > 0)
{
return Instance._pool.Pop();
}
else
{
return new Dictionary<Key, Value>();
}
}
public static void Release(Dictionary<Key, Value> dict)
{
if (dict == null || Instance == null) return;
dict.Clear();
Instance._pool.Push(dict);
}
public void Dispose()
{
if (Instance != null)
{
if (Instance._pool != null)
{
Instance._pool.Clear();
Instance._pool = null;
}
Instance = null;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 59e9f74cfa6aa344c91bcdcc6db78ac6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,140 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace SkierFramework
{
public class PrefabPool
{
/// <summary>
/// 如果名字一样,则使用同一个池子
/// </summary>
public static Dictionary<string, PrefabPool> s_Pools = new Dictionary<string, PrefabPool>();
private string _poolName;
private GameObject _prefab;
private List<GameObject> _pool;
private List<GameObject> _useList;
public GameObject Prefab => _prefab;
public List<GameObject> UseList => _useList;
private PrefabPool() { }
private void Init(string poolName, GameObject prefab)
{
_pool = ListPool<GameObject>.Get();
_useList = ListPool<GameObject>.Get();
_prefab = prefab;
_poolName = poolName;
}
public static PrefabPool Get(string poolName)
{
if (!string.IsNullOrEmpty(poolName))
{
if (s_Pools.TryGetValue(poolName, out var prefabPool))
{
return prefabPool;
}
}
return null;
}
public static PrefabPool Create(GameObject prefab, string poolName = null)
{
if (prefab == null) return null;
if (!string.IsNullOrEmpty(poolName))
{
if (s_Pools.TryGetValue(poolName, out var prefabPool))
{
return prefabPool;
}
}
var pool = new PrefabPool();
pool.Init(poolName, prefab);
if (!string.IsNullOrEmpty(poolName))
{
s_Pools.Add(poolName, pool);
}
return pool;
}
public GameObject Get(Transform parent = null)
{
if (_prefab == null) return null;
GameObject go = null;
if (_pool.Count > 0)
{
go = _pool[0];
_pool.RemoveAt(0);
}
else
{
go = GameObject.Instantiate(_prefab);
}
go.transform.parent = parent;
go.transform.localScale = Vector3.one;
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = Quaternion.identity;
go.SetActive(true);
go.transform.SetAsLastSibling();
_useList.Add(go);
return go;
}
public void Recycle(GameObject go)
{
if (go != null)
{
go.SetActive(false);
_pool.Add(go);
_useList.Remove(go);
}
}
public void RecycleUseList()
{
foreach (var go in _useList)
{
if (go != null)
{
go.SetActive(false);
_pool.Add(go);
}
}
_useList.Clear();
}
public void Destroy()
{
foreach (var go in _pool)
{
if (go != null)
{
GameObject.Destroy(go);
}
}
_pool.Clear();
foreach (var go in _useList)
{
if (go != null)
{
GameObject.Destroy(go);
}
}
_useList.Clear();
ListPool<GameObject>.Release(_pool);
ListPool<GameObject>.Release(_useList);
s_Pools.Remove(_poolName);
_pool = null;
_useList = null;
_prefab = null;
_poolName = null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 02cdac12da067fa479f36e34fafd0987
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,71 @@
using UnityEngine;
public abstract class Singleton<T> where T : new()
{
private static T _ServiceContext;
private readonly static object lockObj = new object();
/// <summary>
/// 禁止外部进行实例化
/// </summary>
protected Singleton()
{
OnInitialize();
}
/// <summary>
/// 获取唯一实例,双锁定防止多线程并发时重复创建实例
/// </summary>
/// <returns></returns>
public static T Instance
{
get
{
if (_ServiceContext == null)
{
lock (lockObj)
{
if (_ServiceContext == null)
{
_ServiceContext = new T();
}
}
}
return _ServiceContext;
}
}
public virtual void OnInitialize() { }
public void Init() { }
}
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = (T)FindObjectOfType(typeof(T));
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = typeof(T).ToString();
DontDestroyOnLoad(singleton);
}
}
return _instance;
}
}
public virtual void OnDestroy()
{
_instance = null;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 26a0ecd7bd1fa9441a7229d39408180c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
namespace SkierFramework
{
public class TreeNode
{
public Dictionary<ulong, TreeNode> childs;
public ulong id;
public object data;
public TreeNode Get(ulong id)
{
if (childs == null)
{
return null;
}
childs.TryGetValue(id, out var node);
return node;
}
public TreeNode GetOrAdd(ulong id)
{
if (childs == null)
{
childs = new Dictionary<ulong, TreeNode>();
}
if (!childs.TryGetValue(id, out var node))
{
node = ObjectPool<TreeNode>.Get();
node.id = id;
childs.Add(id, node);
}
return node;
}
public void CleanUp()
{
if (childs != null)
{
foreach (var item in childs.Values)
{
item.CleanUp();
ObjectPool<TreeNode>.Release(item);
}
childs.Clear();
}
id = 0;
data = default;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dc97d6286a198a946a032cc4fa7fe2cf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d1c08d26fe3fa4740b2a4398ea9ee65b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace SkierFramework
{
public class InstancePool
{
private static string GameObjectName = "GameObjectPool";
private static string RecycleName = "RecyclePool";
private Dictionary<string, Stack<GameObject>> _allInstances = new Dictionary<string, Stack<GameObject>>();
private Transform _instancePoolTransRoot = null;
private Transform _recyclePoolTransRoot = null;
public InstancePool()
{
var go = new GameObject(GameObjectName);
GameObject.DontDestroyOnLoad(go);
_instancePoolTransRoot = go.transform;
go.SetActive(true);
_recyclePoolTransRoot = _instancePoolTransRoot.Find(RecycleName);
if (_recyclePoolTransRoot == null)
{
_recyclePoolTransRoot = new GameObject(RecycleName).transform;
_recyclePoolTransRoot.SetParent(_instancePoolTransRoot);
}
_recyclePoolTransRoot.gameObject.SetActive(false);
}
public GameObject Get(string key)
{
Stack<GameObject> objects = null;
if (!_allInstances.TryGetValue(key, out objects))
{
return null;
}
else
{
if (objects == null || objects.Count == 0)
{
return null;
}
return objects.Pop();
}
}
public void Recycle(string key, GameObject obj, bool forceDestroy = false)
{
//强制删除
if (forceDestroy)
{
if (Application.isPlaying)
{
GameObject.Destroy(obj);
}
else
{
GameObject.DestroyImmediate(obj);
}
return;
}
Stack<GameObject> objects = null;
if (!_allInstances.TryGetValue(key, out objects))
{
objects = new Stack<GameObject>();
_allInstances[key] = objects;
}
InitInst(obj, false);
objects.Push(obj);
}
public void Clear(string key)
{
Stack<GameObject> objects = null;
if (_allInstances.TryGetValue(key, out objects))
{
while (objects.Count > 0)
{
GameObject objToDestroy = objects.Pop();
if (Application.isPlaying)
{
GameObject.Destroy(objToDestroy);
}
else
{
GameObject.DestroyImmediate(objToDestroy);
}
}
}
}
public void ClearAll()
{
foreach (var item in _allInstances)
{
while (item.Value.Count > 0)
{
GameObject objToDestroy = item.Value.Pop();
if (Application.isPlaying)
{
GameObject.Destroy(objToDestroy);
}
else
{
GameObject.DestroyImmediate(objToDestroy);
}
}
}
_allInstances.Clear();
}
public void InitInst(GameObject inst, bool active = true)
{
if (inst != null)
{
if (active)
{
inst.transform.SetParent(_instancePoolTransRoot, true);
}
else
{
inst.transform.SetParent(_recyclePoolTransRoot, true);
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b78b11e8c4a134f478ab61d5c6334deb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9400821223fb8b04bb736c2141678f00
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,49 @@
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SkierFramework
{
public class ResourceManager : Singleton<ResourceManager>
{
private Dictionary<string, ResourceCore> _resourceCore;
public override void OnInitialize()
{
base.OnInitialize();
_resourceCore = new Dictionary<string, ResourceCore>();
}
public ResourceCore GetResourceCore(string packageName)
{
if (_resourceCore.TryGetValue(packageName, out ResourceCore resourceCore))
{
return resourceCore;
}
else
{
return AddResourceCore(packageName);
}
}
public ResourceCore AddResourceCore(string packageName)
{
if (_resourceCore.TryGetValue(packageName, out var core))
{
return core;
}
var resourceCore = new ResourceCore();
_resourceCore.Add(packageName, resourceCore);
return resourceCore;
}
public void RemoveResourceCore(string packageName)
{
if (_resourceCore.ContainsKey(packageName))
{
_resourceCore[packageName] = null;
_resourceCore.Remove(packageName);
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ca68341749364957bb8dc9ca55575f79
timeCreated: 1758017241
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ae09f872dbca2d84fa2a065b22315aef
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,5 @@
fileFormatVersion: 2
guid: a6bdd27938945f0449bc8fe7947f2bf2
folderAsset: yes
DefaultImporter:
userData:
@@ -0,0 +1,135 @@
using UnityEngine;
/// <summary>
/// Tween the object's alpha. Works with both UI widgets as well as renderers.
/// </summary>
[AddComponentMenu("Tween/Tween Alpha")]
public class TweenAlpha : UITweener
{
[Range(0f, 1f)] public float from = 1f;
[Range(0f, 1f)] public float to = 1f;
[Tooltip("If used on a renderer, the material should probably be cleaned up after this script gets destroyed...")]
public bool autoCleanup = false;
[Tooltip("Color to adjust")]
public string colorProperty;
[System.NonSerialized] bool mCached = false;
[System.NonSerialized] CanvasGroup mRect;
[System.NonSerialized] Material mShared;
[System.NonSerialized] Material mMat;
[System.NonSerialized] Light mLight;
[System.NonSerialized] SpriteRenderer mSr;
[System.NonSerialized] float mBaseIntensity = 1f;
[System.Obsolete("Use 'value' instead")]
public float alpha { get { return this.value; } set { this.value = value; } }
void OnDestroy () { if (autoCleanup && mMat != null && mShared != mMat) { Destroy(mMat); mMat = null; } }
void Cache ()
{
mCached = true;
mRect = GetComponent<CanvasGroup>();
mSr = GetComponent<SpriteRenderer>();
if (mRect == null && mSr == null)
{
mLight = GetComponent<Light>();
if (mLight == null)
{
var ren = GetComponent<Renderer>();
if (ren != null)
{
mShared = ren.sharedMaterial;
mMat = ren.material;
}
if (mMat == null) mRect = GetComponentInChildren<CanvasGroup>();
}
else mBaseIntensity = mLight.intensity;
}
}
/// <summary>
/// Tween's current value.
/// </summary>
public float value
{
get
{
if (!mCached) Cache();
if (mRect != null) return mRect.alpha;
if (mSr != null) return mSr.color.a;
if (mMat == null) return 1f;
if (string.IsNullOrEmpty(colorProperty)) return mMat.color.a;
return mMat.GetColor(colorProperty).a;
}
set
{
if (!mCached) Cache();
if (mRect != null)
{
mRect.alpha = value;
}
else if (mSr != null)
{
var c = mSr.color;
c.a = value;
mSr.color = c;
}
else if (mMat != null)
{
if (string.IsNullOrEmpty(colorProperty))
{
var c = mMat.color;
c.a = value;
mMat.color = c;
}
else
{
var c = mMat.GetColor(colorProperty);
c.a = value;
mMat.SetColor(colorProperty, c);
}
}
else if (mLight != null)
{
mLight.intensity = mBaseIntensity * value;
}
}
}
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = Mathf.Lerp(from, to, factor); }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenAlpha Begin (GameObject go, float duration, float alpha, float delay = 0f)
{
var comp = UITweener.Begin<TweenAlpha>(go, duration, delay);
comp.from = comp.value;
comp.to = alpha;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
public override void SetStartToCurrentValue () { from = value; }
public override void SetEndToCurrentValue () { to = value; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9e2747e3775af504da1a4d5a46c5a1ce
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,118 @@
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Tween the object's color.
/// </summary>
[AddComponentMenu("Tween/Tween Color")]
public class TweenColor : UITweener
{
public Color from = Color.white;
public Color to = Color.white;
bool mCached = false;
Graphic mGraphic;
Material mMat;
Light mLight;
SpriteRenderer mSr;
void Cache ()
{
mCached = true;
mGraphic = GetComponent<Graphic>();
if (mGraphic != null) return;
mSr = GetComponent<SpriteRenderer>();
if (mSr != null) return;
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
Renderer ren = renderer;
#else
Renderer ren = GetComponent<Renderer>();
#endif
if (ren != null)
{
mMat = ren.material;
return;
}
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
mLight = light;
#else
mLight = GetComponent<Light>();
#endif
if (mLight == null) mGraphic = GetComponentInChildren<Graphic>();
}
[System.Obsolete("Use 'value' instead")]
public Color color { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public Color value
{
get
{
if (!mCached) Cache();
if (mGraphic != null) return mGraphic.color;
if (mMat != null) return mMat.color;
if (mSr != null) return mSr.color;
if (mLight != null) return mLight.color;
return Color.black;
}
set
{
if (!mCached) Cache();
if (mGraphic != null) mGraphic.color = value;
else if (mMat != null) mMat.color = value;
else if (mSr != null) mSr.color = value;
else if (mLight != null)
{
mLight.color = value;
mLight.enabled = (value.r + value.g + value.b) > 0.01f;
}
}
}
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = Color.Lerp(from, to, factor); }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenColor Begin (GameObject go, float duration, Color color)
{
#if UNITY_EDITOR
if (!Application.isPlaying) return null;
#endif
TweenColor comp = UITweener.Begin<TweenColor>(go, duration);
comp.from = comp.value;
comp.to = color;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cfa4a4a103e4fed43a7e9e9df4a6915c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,66 @@
using UnityEngine;
/// <summary>
/// Tween the camera's field of view.
/// </summary>
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Tween/Tween Field of View")]
public class TweenFOV : UITweener
{
public float from = 45f;
public float to = 45f;
Camera mCam;
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
public Camera cachedCamera { get { if (mCam == null) mCam = camera; return mCam; } }
#else
public Camera cachedCamera { get { if (mCam == null) mCam = GetComponent<Camera>(); return mCam; } }
#endif
[System.Obsolete("Use 'value' instead")]
public float fov { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public float value { get { return cachedCamera.fieldOfView; } set { cachedCamera.fieldOfView = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = from * (1f - factor) + to * factor; }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenFOV Begin (GameObject go, float duration, float to)
{
TweenFOV comp = UITweener.Begin<TweenFOV>(go, duration);
comp.from = comp.value;
comp.to = to;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0153adb55685cee4d97c4ee2d52124e5
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,69 @@
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Tween the Image fill.
/// </summary>
[RequireComponent(typeof(Image))]
[AddComponentMenu("Tween/Tween Fill")]
public class TweenFill : UITweener
{
[Range(0f, 1f)] public float from = 1f;
[Range(0f, 1f)] public float to = 1f;
bool mCached = false;
Image mSprite;
void Cache ()
{
mCached = true;
mSprite = GetComponent<Image>();
}
/// <summary>
/// Tween's current value.
/// </summary>
public float value
{
get
{
if (!mCached) Cache();
if (mSprite != null) return mSprite.fillAmount;
return 0f;
}
set
{
if (!mCached) Cache();
if (mSprite != null) mSprite.fillAmount = value;
}
}
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = Mathf.Lerp(from, to, factor); }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenFill Begin (GameObject go, float duration, float fill)
{
TweenFill comp = UITweener.Begin<TweenFill>(go, duration);
comp.from = comp.value;
comp.to = fill;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
public override void SetStartToCurrentValue () { from = value; }
public override void SetEndToCurrentValue () { to = value; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6ba7f59a1f412544f85ac3e66f0b5227
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,74 @@
using UnityEngine;
/// <summary>
/// Tween the widget's size.
/// </summary>
[RequireComponent(typeof(RectTransform))]
[AddComponentMenu("Tween/Tween Height")]
public class TweenHeight : UITweener
{
public float from = 100;
public float to = 100;
[Tooltip("If set, 'from' value will be set to match the specified rectangle")]
public RectTransform fromTarget;
[Tooltip("If set, 'to' value will be set to match the specified rectangle")]
public RectTransform toTarget;
RectTransform mWidget;
public RectTransform cachedWidget { get { if (mWidget == null) mWidget = GetComponent<RectTransform>(); return mWidget; } }
[System.Obsolete("Use 'value' instead")]
public float height { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public float value { get { return cachedWidget.rect.height; } set { cachedWidget.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, value); } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
if (fromTarget) from = fromTarget.rect.width;
if (toTarget) to = toTarget.rect.width;
value = Mathf.RoundToInt(from * (1f - factor) + to * factor);
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenHeight Begin (RectTransform widget, float duration, int height)
{
TweenHeight comp = UITweener.Begin<TweenHeight>(widget.gameObject, duration);
comp.from = widget.rect.height;
comp.to = height;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 66a6ab21c5f860946ade65b47cc0270b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: -92
icon: {instanceID: 0}
userData:
@@ -0,0 +1,65 @@
using UnityEngine;
/// <summary>
/// Tween the camera's orthographic size.
/// </summary>
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Tween/Tween Orthographic Size")]
public class TweenOrthoSize : UITweener
{
public float from = 1f;
public float to = 1f;
Camera mCam;
/// <summary>
/// Camera that's being tweened.
/// </summary>
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
public Camera cachedCamera { get { if (mCam == null) mCam = camera; return mCam; } }
#else
public Camera cachedCamera { get { if (mCam == null) mCam = GetComponent<Camera>(); return mCam; } }
#endif
[System.Obsolete("Use 'value' instead")]
public float orthoSize { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public float value
{
get { return cachedCamera.orthographicSize; }
set { cachedCamera.orthographicSize = value; }
}
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = from * (1f - factor) + to * factor; }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenOrthoSize Begin (GameObject go, float duration, float to)
{
TweenOrthoSize comp = UITweener.Begin<TweenOrthoSize>(go, duration);
comp.from = comp.value;
comp.to = to;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
public override void SetStartToCurrentValue () { from = value; }
public override void SetEndToCurrentValue () { to = value; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 365827806a6dd8b4583deeefe6e483c9
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,94 @@
using UnityEngine;
/// <summary>
/// Tween the object's position.
/// </summary>
[AddComponentMenu("Tween/Tween Position")]
public class TweenPosition : UITweener
{
public Vector3 from;
public Vector3 to;
[HideInInspector]
public bool worldSpace = false;
Transform mTrans;
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
[System.Obsolete("Use 'value' instead")]
public Vector3 position { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public Vector3 value
{
get
{
return worldSpace ? cachedTransform.position : cachedTransform.localPosition;
}
set
{
if (worldSpace) cachedTransform.position = value;
else cachedTransform.localPosition = value;
}
}
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = from * (1f - factor) + to * factor; }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenPosition Begin (GameObject go, float duration, Vector3 pos)
{
TweenPosition comp = UITweener.Begin<TweenPosition>(go, duration);
comp.from = comp.value;
comp.to = pos;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenPosition Begin (GameObject go, float duration, Vector3 pos, bool worldSpace)
{
TweenPosition comp = UITweener.Begin<TweenPosition>(go, duration);
comp.worldSpace = worldSpace;
comp.from = comp.value;
comp.to = pos;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3d166255cacf07b4292b8402b3ddefc5
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: -98
icon: {instanceID: 0}
userData:
@@ -0,0 +1,69 @@
using UnityEngine;
/// <summary>
/// Tween the object's rotation.
/// </summary>
[AddComponentMenu("Tween/Tween Rotation")]
public class TweenRotation : UITweener
{
public Vector3 from;
public Vector3 to;
public bool quaternionLerp = false;
Transform mTrans;
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
[System.Obsolete("Use 'value' instead")]
public Quaternion rotation { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public Quaternion value { get { return cachedTransform.localRotation; } set { cachedTransform.localRotation = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
value = quaternionLerp ? Quaternion.Slerp(Quaternion.Euler(from), Quaternion.Euler(to), factor) :
Quaternion.Euler(new Vector3(
Mathf.Lerp(from.x, to.x, factor),
Mathf.Lerp(from.y, to.y, factor),
Mathf.Lerp(from.z, to.z, factor)));
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenRotation Begin (GameObject go, float duration, Quaternion rot)
{
TweenRotation comp = UITweener.Begin<TweenRotation>(go, duration);
comp.from = comp.value.eulerAngles;
comp.to = rot.eulerAngles;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value.eulerAngles; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value.eulerAngles; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = Quaternion.Euler(from); }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = Quaternion.Euler(to); }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 04d1b7c9e9a19a24ab67123a43c6544b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: -95
icon: {instanceID: 0}
userData:
@@ -0,0 +1,60 @@
using UnityEngine;
/// <summary>
/// Tween the object's local scale.
/// </summary>
[AddComponentMenu("Tween/Tween Scale")]
public class TweenScale : UITweener
{
public Vector3 from = Vector3.one;
public Vector3 to = Vector3.one;
Transform mTrans;
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
public Vector3 value { get { return cachedTransform.localScale; } set { cachedTransform.localScale = value; } }
[System.Obsolete("Use 'value' instead")]
public Vector3 scale { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
value = from * (1f - factor) + to * factor;
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenScale Begin (GameObject go, float duration, Vector3 scale)
{
TweenScale comp = UITweener.Begin<TweenScale>(go, duration);
comp.from = comp.value;
comp.to = scale;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 75e7459110b9666449485c40f25362a5
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: -94
icon: {instanceID: 0}
userData:
@@ -0,0 +1,76 @@
using UnityEngine;
/// <summary>
/// Tween the object's position, rotation and scale.
/// </summary>
[AddComponentMenu("Tween/Tween Transform")]
public class TweenTransform : UITweener
{
public Transform from;
public Transform to;
public bool parentWhenFinished = false;
Transform mTrans;
Vector3 mPos;
Quaternion mRot;
Vector3 mScale;
/// <summary>
/// Interpolate the position, scale, and rotation.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
if (to != null)
{
if (mTrans == null)
{
mTrans = transform;
mPos = mTrans.position;
mRot = mTrans.rotation;
mScale = mTrans.localScale;
}
if (from != null)
{
mTrans.position = from.position * (1f - factor) + to.position * factor;
mTrans.localScale = from.localScale * (1f - factor) + to.localScale * factor;
mTrans.rotation = Quaternion.Slerp(from.rotation, to.rotation, factor);
}
else
{
mTrans.position = mPos * (1f - factor) + to.position * factor;
mTrans.localScale = mScale * (1f - factor) + to.localScale * factor;
mTrans.rotation = Quaternion.Slerp(mRot, to.rotation, factor);
}
// Change the parent when finished, if requested
if (parentWhenFinished && isFinished) mTrans.parent = to;
}
}
/// <summary>
/// Start the tweening operation from the current position/rotation/scale to the target transform.
/// </summary>
static public TweenTransform Begin (GameObject go, float duration, Transform to) { return Begin(go, duration, null, to); }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenTransform Begin (GameObject go, float duration, Transform from, Transform to)
{
TweenTransform comp = UITweener.Begin<TweenTransform>(go, duration);
comp.from = from;
comp.to = to;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1d805c79a1ab11643bfd9d91e10c195a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,89 @@
using UnityEngine;
/// <summary>
/// Tween the audio source's volume.
/// </summary>
[RequireComponent(typeof(AudioSource))]
[AddComponentMenu("Tween/Tween Volume")]
public class TweenVolume : UITweener
{
[Range(0f, 1f)] public float from = 1f;
[Range(0f, 1f)] public float to = 1f;
AudioSource mSource;
/// <summary>
/// Cached version of 'audio', as it's always faster to cache.
/// </summary>
public AudioSource audioSource
{
get
{
if (mSource == null)
{
mSource = GetComponent<AudioSource>();
if (mSource == null)
{
mSource = GetComponent<AudioSource>();
if (mSource == null)
{
Debug.LogError("TweenVolume needs an AudioSource to work with", this);
enabled = false;
}
}
}
return mSource;
}
}
[System.Obsolete("Use 'value' instead")]
public float volume { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Audio source's current volume.
/// </summary>
public float value
{
get
{
return audioSource != null ? mSource.volume : 0f;
}
set
{
if (audioSource != null) mSource.volume = value;
}
}
protected override void OnUpdate (float factor, bool isFinished)
{
value = from * (1f - factor) + to * factor;
mSource.enabled = (mSource.volume > 0.01f);
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenVolume Begin (GameObject go, float duration, float targetVolume)
{
TweenVolume comp = UITweener.Begin<TweenVolume>(go, duration);
comp.from = comp.value;
comp.to = targetVolume;
if (targetVolume > 0f)
{
var s = comp.audioSource;
s.enabled = true;
s.Play();
}
return comp;
}
public override void SetStartToCurrentValue () { from = value; }
public override void SetEndToCurrentValue () { to = value; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 17aeef7ce6c142344959e650cab20151
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,75 @@
using UnityEngine;
/// <summary>
/// Tween the widget's size.
/// </summary>
[RequireComponent(typeof(RectTransform))]
[AddComponentMenu("Tween/Tween Width")]
public class TweenWidth : UITweener
{
public float from = 100;
public float to = 100;
[Tooltip("If set, 'from' value will be set to match the specified rectangle")]
public RectTransform fromTarget;
[Tooltip("If set, 'to' value will be set to match the specified rectangle")]
public RectTransform toTarget;
RectTransform mWidget;
RectTransform mTable;
public RectTransform cachedWidget { get { if (mWidget == null) mWidget = GetComponent<RectTransform>(); return mWidget; } }
[System.Obsolete("Use 'value' instead")]
public float width { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public float value { get { return cachedWidget.rect.width; } set { cachedWidget.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, value); } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
if (fromTarget) from = fromTarget.rect.width;
if (toTarget) to = toTarget.rect.width;
value = Mathf.RoundToInt(from * (1f - factor) + to * factor);
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenWidth Begin (RectTransform widget, float duration, int width)
{
var comp = UITweener.Begin<TweenWidth>(widget.gameObject, duration);
comp.from = widget.rect.width;
comp.to = width;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0fe5d396737f89f4ea1534bc147cad2e
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: -93
icon: {instanceID: 0}
userData:
@@ -0,0 +1,531 @@
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Base class for all tweening operations.
/// </summary>
public abstract class UITweener : MonoBehaviour
{
/// <summary>
/// Current tween that triggered the callback function.
/// </summary>
static public UITweener current;
public enum Method
{
Linear,
EaseIn,
EaseOut,
EaseInOut,
BounceIn,
BounceOut,
}
public enum Style
{
Once,
Loop,
PingPong,
}
/// <summary>
/// Tweening method used.
/// </summary>
[HideInInspector]
public Method method = Method.Linear;
/// <summary>
/// Does it play once? Does it loop?
/// </summary>
[HideInInspector]
public Style style = Style.Once;
/// <summary>
/// Optional curve to apply to the tween's time factor value.
/// </summary>
[HideInInspector]
public AnimationCurve animationCurve = new AnimationCurve(new Keyframe(0f, 0f, 0f, 1f), new Keyframe(1f, 1f, 1f, 0f));
/// <summary>
/// Whether the tween will ignore the timescale, making it work while the game is paused.
/// </summary>
[HideInInspector]
public bool ignoreTimeScale = true;
/// <summary>
/// How long will the tweener wait before starting the tween?
/// </summary>
[HideInInspector]
public float delay = 0f;
public enum DelayAffects
{
Forward,
Reverse,
Both,
}
[HideInInspector]
public DelayAffects delayAffects = DelayAffects.Both;
/// <summary>
/// How long is the duration of the tween?
/// </summary>
[HideInInspector]
public float duration = 1f;
/// <summary>
/// Whether the tweener will use steeper curves for ease in / out style interpolation.
/// </summary>
[HideInInspector]
public bool steeperCurves = false;
/// <summary>
/// Used by buttons and tween sequences. Group of '0' means not in a sequence.
/// </summary>
[HideInInspector]
public int tweenGroup = 0;
[Tooltip("By default, Update() will be used for tweening. Setting this to 'true' will make the tween happen in FixedUpdate() insted.")]
public bool useFixedUpdate = false;
/// <summary>
/// Event delegates called when the animation finishes.
/// </summary>
//[HideInInspector]
//public List<EventDelegate> onFinished = new List<EventDelegate>();
// Deprecated functionality, kept for backwards compatibility
[HideInInspector] public GameObject eventReceiver;
[HideInInspector] public string callWhenFinished;
/// <summary>
/// Custom time scale for this tween, if desired. Can be used to slow down or speed up the animation.
/// </summary>
[System.NonSerialized] public float timeScale = 1f;
bool mStarted = false;
float mStartTime = 0f;
float mDuration = 0f;
float mAmountPerDelta = 1000f;
float mFactor = 0f;
/// <summary>
/// Amount advanced per delta time.
/// </summary>
public float amountPerDelta
{
get
{
if (duration == 0f) return 1000f;
if (mDuration != duration)
{
mDuration = duration;
mAmountPerDelta = Mathf.Abs(1f / duration) * Mathf.Sign(mAmountPerDelta);
}
return mAmountPerDelta;
}
}
/// <summary>
/// Tween factor, 0-1 range.
/// </summary>
public float tweenFactor { get { return mFactor; } set { mFactor = Mathf.Clamp01(value); } }
/// <summary>
/// Direction that the tween is currently playing in.
/// </summary>
//public AnimationOrTween.Direction direction { get { return amountPerDelta < 0f ? AnimationOrTween.Direction.Reverse : AnimationOrTween.Direction.Forward; } }
/// <summary>
/// This function is called by Unity when you add a component. Automatically set the starting values for convenience.
/// </summary>
void Reset ()
{
if (!mStarted)
{
SetStartToCurrentValue();
SetEndToCurrentValue();
}
}
/// <summary>
/// Update as soon as it's started so that there is no delay.
/// </summary>
protected virtual void Start () { DoUpdate(); }
protected void Update () { if (!useFixedUpdate) DoUpdate(); }
protected void FixedUpdate () { if (useFixedUpdate) DoUpdate(); }
/// <summary>
/// Update the tweening factor and call the virtual update function.
/// </summary>
protected void DoUpdate ()
{
float delta = ignoreTimeScale && !useFixedUpdate ? Time.unscaledDeltaTime : Time.deltaTime;
float time = ignoreTimeScale && !useFixedUpdate ? Time.unscaledTime : Time.time;
if (!mStarted)
{
delta = 0;
mStarted = true;
mStartTime = time;
if (mAmountPerDelta > 0f && (delayAffects == DelayAffects.Both || delayAffects == DelayAffects.Forward)) mStartTime += delay;
else if (mAmountPerDelta < 0f && (delayAffects == DelayAffects.Both || delayAffects == DelayAffects.Reverse)) mStartTime += delay;
}
if (time < mStartTime) return;
// Advance the sampling factor
mFactor += (duration == 0f) ? 1f : amountPerDelta * delta * timeScale;
// Loop style simply resets the play factor after it exceeds 1.
if (style == Style.Loop)
{
if (mFactor > 1f)
{
mFactor -= Mathf.Floor(mFactor);
}
}
else if (style == Style.PingPong)
{
// Ping-pong style reverses the direction
if (mFactor > 1f)
{
mFactor = 1f - (mFactor - Mathf.Floor(mFactor));
mAmountPerDelta = -mAmountPerDelta;
}
else if (mFactor < 0f)
{
mFactor = -mFactor;
mFactor -= Mathf.Floor(mFactor);
mAmountPerDelta = -mAmountPerDelta;
}
}
// If the factor goes out of range and this is a one-time tweening operation, disable the script
if ((style == Style.Once) && (duration == 0f || mFactor > 1f || mFactor < 0f))
{
mFactor = Mathf.Clamp01(mFactor);
Sample(mFactor, true);
enabled = false;
if (current != this)
{
UITweener before = current;
current = this;
//if (onFinished != null)
//{
// mTemp = onFinished;
// onFinished = new List<EventDelegate>();
// // Notify the listener delegates
// EventDelegate.Execute(mTemp);
// // Re-add the previous persistent delegates
// for (int i = 0; i < mTemp.Count; ++i)
// {
// EventDelegate ed = mTemp[i];
// if (ed != null && !ed.oneShot) EventDelegate.Add(onFinished, ed, ed.oneShot);
// }
// mTemp = null;
//}
// Deprecated legacy functionality support
if (eventReceiver != null && !string.IsNullOrEmpty(callWhenFinished))
eventReceiver.SendMessage(callWhenFinished, this, SendMessageOptions.DontRequireReceiver);
current = before;
}
}
else Sample(mFactor, false);
}
//List<EventDelegate> mTemp = null;
/// <summary>
/// Convenience function -- set a new OnFinished event delegate (here for to be consistent with RemoveOnFinished).
/// </summary>
//public void SetOnFinished (EventDelegate.Callback del) { EventDelegate.Set(onFinished, del); }
///// <summary>
///// Convenience function -- set a new OnFinished event delegate (here for to be consistent with RemoveOnFinished).
///// </summary>
//public void SetOnFinished (EventDelegate del) { EventDelegate.Set(onFinished, del); }
///// <summary>
///// Convenience function -- add a new OnFinished event delegate (here for to be consistent with RemoveOnFinished).
///// </summary>
//public void AddOnFinished (EventDelegate.Callback del) { EventDelegate.Add(onFinished, del); }
///// <summary>
///// Convenience function -- add a new OnFinished event delegate (here for to be consistent with RemoveOnFinished).
///// </summary>
//public void AddOnFinished (EventDelegate del) { EventDelegate.Add(onFinished, del); }
///// <summary>
///// Remove an OnFinished delegate. Will work even while iterating through the list when the tweener has finished its operation.
///// </summary>
//public void RemoveOnFinished (EventDelegate del)
//{
// if (onFinished != null) onFinished.Remove(del);
// if (mTemp != null) mTemp.Remove(del);
//}
/// <summary>
/// Mark as not started when finished to enable delay on next play.
/// </summary>
protected virtual void OnDisable () { mStarted = false; }
/// <summary>
/// Immediately finish the tween animation, if it's active.
/// </summary>
public void Finish ()
{
if (enabled)
{
Sample(mAmountPerDelta > 0f ? 1f : 0f, true);
enabled = false;
}
}
/// <summary>
/// Sample the tween at the specified factor.
/// </summary>
public void Sample (float factor, bool isFinished)
{
// Calculate the sampling value
float val = Mathf.Clamp01(factor);
if (method == Method.EaseIn)
{
val = 1f - Mathf.Sin(0.5f * Mathf.PI * (1f - val));
if (steeperCurves) val *= val;
}
else if (method == Method.EaseOut)
{
val = Mathf.Sin(0.5f * Mathf.PI * val);
if (steeperCurves)
{
val = 1f - val;
val = 1f - val * val;
}
}
else if (method == Method.EaseInOut)
{
const float pi2 = Mathf.PI * 2f;
val = val - Mathf.Sin(val * pi2) / pi2;
if (steeperCurves)
{
val = val * 2f - 1f;
float sign = Mathf.Sign(val);
val = 1f - Mathf.Abs(val);
val = 1f - val * val;
val = sign * val * 0.5f + 0.5f;
}
}
else if (method == Method.BounceIn)
{
val = BounceLogic(val);
}
else if (method == Method.BounceOut)
{
val = 1f - BounceLogic(1f - val);
}
// Call the virtual update
OnUpdate((animationCurve != null) ? animationCurve.Evaluate(val) : val, isFinished);
}
/// <summary>
/// Main Bounce logic to simplify the Sample function
/// </summary>
float BounceLogic (float val)
{
if (val < 0.363636f) // 0.363636 = (1/ 2.75)
{
val = 7.5685f * val * val;
}
else if (val < 0.727272f) // 0.727272 = (2 / 2.75)
{
val = 7.5625f * (val -= 0.545454f) * val + 0.75f; // 0.545454f = (1.5 / 2.75)
}
else if (val < 0.909090f) // 0.909090 = (2.5 / 2.75)
{
val = 7.5625f * (val -= 0.818181f) * val + 0.9375f; // 0.818181 = (2.25 / 2.75)
}
else
{
val = 7.5625f * (val -= 0.9545454f) * val + 0.984375f; // 0.9545454 = (2.625 / 2.75)
}
return val;
}
/// <summary>
/// Play the tween.
/// </summary>
[System.Obsolete("Use PlayForward() instead")]
public void Play () { Play(true); }
/// <summary>
/// Play the tween forward.
/// </summary>
[ContextMenu("Play forward")]
public void PlayForward () { Play(true); }
/// <summary>
/// Play the tween in reverse.
/// </summary>
[ContextMenu("Play in reverse")]
public void PlayReverse () { Play(false); }
/// <summary>
/// Manually activate the tweening process, reversing it if necessary.
/// </summary>
public virtual void Play (bool forward)
{
mAmountPerDelta = Mathf.Abs(amountPerDelta);
if (!forward) mAmountPerDelta = -mAmountPerDelta;
if (!enabled)
{
enabled = true;
mStarted = false;
}
DoUpdate();
}
/// <summary>
/// Manually reset the tweener's state to the beginning.
/// If the tween is playing forward, this means the tween's start.
/// If the tween is playing in reverse, this means the tween's end.
/// </summary>
public void ResetToBeginning ()
{
mStarted = false;
mFactor = (amountPerDelta < 0f) ? 1f : 0f;
Sample(mFactor, false);
}
/// <summary>
/// Manually start the tweening process, reversing its direction.
/// </summary>
public void Toggle ()
{
if (mFactor > 0f)
{
mAmountPerDelta = -amountPerDelta;
}
else
{
mAmountPerDelta = Mathf.Abs(amountPerDelta);
}
enabled = true;
}
/// <summary>
/// Actual tweening logic should go here.
/// </summary>
abstract protected void OnUpdate (float factor, bool isFinished);
/// <summary>
/// Starts the tweening operation.
/// </summary>
static public T Begin<T> (GameObject go, float duration, float delay = 0f) where T : UITweener
{
T comp = go.GetComponent<T>();
#if UNITY_FLASH
if ((object)comp == null) comp = (T)go.AddComponent<T>();
#else
// Find the tween with an unset group ID (group ID of 0).
if (comp != null && comp.tweenGroup != 0)
{
comp = null;
T[] comps = go.GetComponents<T>();
for (int i = 0, imax = comps.Length; i < imax; ++i)
{
comp = comps[i];
if (comp != null && comp.tweenGroup == 0) break;
comp = null;
}
}
if (comp == null)
{
comp = go.AddComponent<T>();
if (comp == null)
{
//Debug.LogError("Unable to add " + typeof(T) + " to " + NGUITools.GetHierarchy(go), go);
return null;
}
}
#endif
comp.mStarted = false;
comp.mFactor = 0f;
comp.duration = duration;
comp.mDuration = duration;
comp.delay = delay;
comp.mAmountPerDelta = duration > 0f ? Mathf.Abs(1f / duration) : 1000f;
comp.style = Style.Once;
comp.animationCurve = new AnimationCurve(new Keyframe(0f, 0f, 0f, 1f), new Keyframe(1f, 1f, 1f, 0f));
comp.eventReceiver = null;
comp.callWhenFinished = null;
//comp.onFinished.Clear();
//if (comp.mTemp != null) comp.mTemp.Clear();
comp.enabled = true;
return comp;
}
/// <summary>
/// Set the 'from' value to the current one.
/// </summary>
public virtual void SetStartToCurrentValue () { }
/// <summary>
/// Set the 'to' value to the current one.
/// </summary>
public virtual void SetEndToCurrentValue () { }
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c96860f5597f2494abb42d29cdca0bcc
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,111 @@
using System;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
namespace SkierFramework
{
public enum UIAdaptType
{
All,
LeftOrTop,
RightOrBottom,
}
public class UIAdapter : MonoBehaviour
{
public UIAdaptType uIAdaptType = UIAdaptType.All;
private float cd;
private void Update()
{
// 为避免旋转屏幕,华为分屏机等导致分辨率变化,且安全区变化的问题,需要持续检测
if (Time.time > cd)
{
InitAdapter();
cd = Time.time + 1;
}
}
private void InitAdapter()
{
var safeArea = Screen.safeArea;
if (UIManager.Instance != null)
{
safeArea = UIManager.Instance.GetSafeArea();
}
var orientation = Screen.orientation;
RectTransform rectTransform = transform as RectTransform;
rectTransform.sizeDelta = Vector2.zero;
if (orientation == ScreenOrientation.LandscapeLeft || orientation == ScreenOrientation.LandscapeRight)
{
switch (uIAdaptType)
{
case UIAdaptType.All:
rectTransform.anchorMin = new Vector2(safeArea.xMin / Screen.width, 0);
rectTransform.anchorMax = new Vector2(safeArea.xMax / Screen.width, 1);
break;
case UIAdaptType.LeftOrTop:
if (orientation == ScreenOrientation.LandscapeLeft)
{
rectTransform.anchorMin = new Vector2(safeArea.xMin / Screen.width, 0);
rectTransform.anchorMax = new Vector2(1, 1);
}
else
{
rectTransform.anchorMin = new Vector2(0, 0);
rectTransform.anchorMax = new Vector2(safeArea.xMax / Screen.width, 1);
}
break;
case UIAdaptType.RightOrBottom:
if (orientation == ScreenOrientation.LandscapeLeft)
{
rectTransform.anchorMin = new Vector2(0, 0);
rectTransform.anchorMax = new Vector2(safeArea.xMax / Screen.width, 1);
}
else
{
rectTransform.anchorMin = new Vector2(safeArea.xMin / Screen.width, 0);
rectTransform.anchorMax = new Vector2(1, 1);
}
break;
}
}
else if (orientation == ScreenOrientation.Portrait || orientation == ScreenOrientation.PortraitUpsideDown)
{
switch (uIAdaptType)
{
case UIAdaptType.All:
rectTransform.anchorMin = new Vector2(0 , safeArea.yMin / Screen.height);
rectTransform.anchorMax = new Vector2(1 , safeArea.yMax / Screen.height);
break;
case UIAdaptType.LeftOrTop:
if (orientation == ScreenOrientation.Portrait)
{
rectTransform.anchorMin = new Vector2(0, 0);
rectTransform.anchorMax = new Vector2(1, safeArea.yMax / Screen.height);
}
else
{
rectTransform.anchorMin = new Vector2(0, safeArea.yMin / Screen.height);
rectTransform.anchorMax = new Vector2(1, 1);
}
break;
case UIAdaptType.RightOrBottom:
if (orientation == ScreenOrientation.Portrait)
{
rectTransform.anchorMin = new Vector2(0, safeArea.yMin / Screen.height);
rectTransform.anchorMax = new Vector2(1, 1);
}
else
{
rectTransform.anchorMin = new Vector2(0, 0);
rectTransform.anchorMax = new Vector2(1, safeArea.yMax / Screen.height);
}
break;
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: efc1aaf05b906ac48b36dd28888f9aac
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dac5f0f85d3930749ac016d6ed29b9dd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 957bc409a9e47584c9c0a315f5c05a0d
folderAsset: yes
timeCreated: 1525057340
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 40733aef832e3a84b84ae9a5b3f74895
folderAsset: yes
timeCreated: 1521786329
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,23 @@
fileFormatVersion: 2
guid: cd170bc15e34a094c8609532aedcc7c9
timeCreated: 1521786330
licenseType: Pro
TrueTypeFontImporter:
externalObjects: {}
serializedVersion: 4
fontSize: 16
forceTextureCase: -2
characterSpacing: 0
characterPadding: 1
includeFontData: 1
fontName: Microsoft YaHei Mono
fontNames:
- Microsoft YaHei Mono
fallbackFontReferences: []
customCharacters:
fontRenderingMode: 0
ascentCalculationMode: 1
useLegacyBoundsCalculation: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: e54e612c85cb2f0438f3fc6849b64d93
timeCreated: 1525054737
licenseType: Pro
NativeFormatImporter:
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show More