提交Unity 联机Pro

This commit is contained in:
PC-20230316NUNE\Administrator
2024-08-17 14:27:18 +08:00
parent f00193b000
commit 894100ae37
7448 changed files with 854473 additions and 0 deletions

View File

@@ -0,0 +1,145 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof (RectTransform))]
[ExecuteInEditMode]
[AddComponentMenu(ComponentMenuPaths.ContentFitText)]
public class ContentFitText : UIBehaviour, ILayoutElement
{
public SRText CopySource;
public Vector2 Padding;
public float minWidth
{
get
{
if (CopySource == null)
{
return -1f;
}
return LayoutUtility.GetMinWidth(CopySource.rectTransform) + Padding.x;
}
}
public float preferredWidth
{
get
{
if (CopySource == null)
{
return -1f;
}
return LayoutUtility.GetPreferredWidth(CopySource.rectTransform) + Padding.x;
}
}
public float flexibleWidth
{
get
{
if (CopySource == null)
{
return -1f;
}
return LayoutUtility.GetFlexibleWidth(CopySource.rectTransform);
}
}
public float minHeight
{
get
{
if (CopySource == null)
{
return -1f;
}
return LayoutUtility.GetFlexibleHeight(CopySource.rectTransform) + Padding.y;
}
}
public float preferredHeight
{
get
{
if (CopySource == null)
{
return -1f;
}
return LayoutUtility.GetPreferredHeight(CopySource.rectTransform) + Padding.y;
}
}
public float flexibleHeight
{
get
{
if (CopySource == null)
{
return -1f;
}
return LayoutUtility.GetFlexibleHeight(CopySource.rectTransform);
}
}
public int layoutPriority
{
get { return 0; }
}
public void CalculateLayoutInputHorizontal()
{
CopySource.CalculateLayoutInputHorizontal();
}
public void CalculateLayoutInputVertical()
{
CopySource.CalculateLayoutInputVertical();
}
protected override void OnEnable()
{
SetDirty();
CopySource.LayoutDirty += CopySourceOnLayoutDirty;
}
private void CopySourceOnLayoutDirty(SRText srText)
{
SetDirty();
}
protected override void OnTransformParentChanged()
{
SetDirty();
}
protected override void OnDisable()
{
CopySource.LayoutDirty -= CopySourceOnLayoutDirty;
SetDirty();
}
protected override void OnDidApplyAnimationProperties()
{
SetDirty();
}
protected override void OnBeforeTransformParentChanged()
{
SetDirty();
}
protected void SetDirty()
{
if (!IsActive())
{
return;
}
LayoutRebuilder.MarkLayoutForRebuild(transform as RectTransform);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dced79525dbfa2b44b8d52b2cca6d745
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,95 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// Copies the preferred size of another layout element (useful for a parent object basing its sizing from a child
/// element).
/// This does have very quirky behaviour, though.
/// TODO: Write custom editor for this to match layout element editor
/// </summary>
[RequireComponent(typeof (RectTransform))]
[ExecuteInEditMode]
[AddComponentMenu(ComponentMenuPaths.CopyLayoutElement)]
public class CopyLayoutElement : UIBehaviour, ILayoutElement
{
public bool CopyMinHeight;
public bool CopyMinWidth;
public bool CopyPreferredHeight;
public bool CopyPreferredWidth;
public RectTransform CopySource;
public float PaddingMinHeight;
public float PaddingMinWidth;
public float PaddingPreferredHeight;
public float PaddingPreferredWidth;
public float preferredWidth
{
get
{
if (!CopyPreferredWidth || CopySource == null || !IsActive())
{
return -1f;
}
return LayoutUtility.GetPreferredWidth(CopySource) + PaddingPreferredWidth;
}
}
public float preferredHeight
{
get
{
if (!CopyPreferredHeight || CopySource == null || !IsActive())
{
return -1f;
}
return LayoutUtility.GetPreferredHeight(CopySource) + PaddingPreferredHeight;
}
}
public float minWidth
{
get
{
if (!CopyMinWidth || CopySource == null || !IsActive())
{
return -1f;
}
return LayoutUtility.GetMinWidth(CopySource) + PaddingMinWidth;
}
}
public float minHeight
{
get
{
if (!CopyMinHeight || CopySource == null || !IsActive())
{
return -1f;
}
return LayoutUtility.GetMinHeight(CopySource) + PaddingMinHeight;
}
}
public int layoutPriority
{
get { return 2; }
}
public float flexibleHeight
{
get { return -1; }
}
public float flexibleWidth
{
get { return -1; }
}
public void CalculateLayoutInputHorizontal() {}
public void CalculateLayoutInputVertical() {}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 525a40520606ceb469b7494cb8ddef87
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,50 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Copies the preferred size of another layout element (useful for a parent object basing its sizing from a child
/// element).
/// This does have very quirky behaviour, though.
/// </summary>
[RequireComponent(typeof (RectTransform))]
[ExecuteInEditMode]
[AddComponentMenu(ComponentMenuPaths.CopyPreferredSize)]
public class CopyPreferredSize : LayoutElement
{
public RectTransform CopySource;
public float PaddingHeight;
public float PaddingWidth;
public override float preferredWidth
{
get
{
if (CopySource == null || !IsActive())
{
return -1f;
}
return LayoutUtility.GetPreferredWidth(CopySource) + PaddingWidth;
}
}
public override float preferredHeight
{
get
{
if (CopySource == null || !IsActive())
{
return -1f;
}
return LayoutUtility.GetPreferredHeight(CopySource) + PaddingHeight;
}
}
public override int layoutPriority
{
get { return 2; }
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 32609112f4257a740aa4b920a8556d24
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,107 @@
using System;
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Copies the preferred size of another layout element (useful for a parent object basing its sizing from a child
/// element).
/// This does have very quirky behaviour, though.
/// </summary>
[RequireComponent(typeof(RectTransform))]
[ExecuteInEditMode]
[AddComponentMenu(ComponentMenuPaths.CopyPreferredSizes)]
public class CopyPreferredSizes : LayoutElement
{
public enum Operations
{
Max,
Min
}
[Serializable]
public class CopySource
{
public RectTransform Rect;
public float PaddingHeight;
public float PaddingWidth;
}
public CopySource[] CopySources;
public Operations Operation;
public override float preferredWidth
{
get
{
if (CopySources == null || CopySources.Length == 0 || !IsActive())
{
return -1f;
}
float current = Operation == Operations.Max ? float.MinValue : float.MaxValue;
for (var i = 0; i < CopySources.Length; i++)
{
if (CopySources[i].Rect == null)
continue;
float width = LayoutUtility.GetPreferredWidth(CopySources[i].Rect) + CopySources[i].PaddingWidth;
if (Operation == Operations.Max && width > current)
current = width;
else if (Operation == Operations.Min && width < current)
current = width;
}
// ReSharper disable CompareOfFloatsByEqualityOperator
if (Operation == Operations.Max && current == float.MinValue) return -1;
if (Operation == Operations.Min && current == float.MaxValue) return -1;
// ReSharper restore CompareOfFloatsByEqualityOperator
return current;
}
}
public override float preferredHeight
{
get
{
if (CopySources == null || CopySources.Length == 0 || !IsActive())
{
return -1f;
}
float current = Operation == Operations.Max ? float.MinValue : float.MaxValue;
for (var i = 0; i < CopySources.Length; i++)
{
if (CopySources[i].Rect == null)
continue;
float height = LayoutUtility.GetPreferredHeight(CopySources[i].Rect) + CopySources[i].PaddingHeight;
if (Operation == Operations.Max && height > current)
current = height;
else if (Operation == Operations.Min && height < current)
current = height;
}
// ReSharper disable CompareOfFloatsByEqualityOperator
if (Operation == Operations.Max && current == float.MinValue) return -1;
if (Operation == Operations.Min && current == float.MaxValue) return -1;
// ReSharper restore CompareOfFloatsByEqualityOperator
return current;
}
}
public override int layoutPriority
{
get { return 2; }
}
}
}

View File

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

View File

@@ -0,0 +1,76 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Copies the preferred size of another layout element (useful for a parent object basing its sizing from a child
/// element).
/// This does have very quirky behaviour, though.
/// </summary>
[RequireComponent(typeof(RectTransform))]
[ExecuteInEditMode]
[AddComponentMenu(ComponentMenuPaths.CopySizeIntoLayoutElement)]
public class CopySizeIntoLayoutElement : LayoutElement
{
public RectTransform CopySource;
public float PaddingHeight;
public float PaddingWidth;
public bool SetPreferredSize = false;
public bool SetMinimumSize = false;
public override float preferredWidth
{
get
{
if (!SetPreferredSize || CopySource == null || !IsActive())
{
return -1f;
}
return CopySource.rect.width + PaddingWidth;
}
}
public override float preferredHeight
{
get
{
if (!SetPreferredSize || CopySource == null || !IsActive())
{
return -1f;
}
return CopySource.rect.height + PaddingHeight;
}
}
public override float minWidth
{
get
{
if (!SetMinimumSize || CopySource == null || !IsActive())
{
return -1f;
}
return CopySource.rect.width + PaddingWidth;
}
}
public override float minHeight
{
get
{
if (!SetMinimumSize || CopySource == null || !IsActive())
{
return -1f;
}
return CopySource.rect.height + PaddingHeight;
}
}
public override int layoutPriority
{
get { return 2; }
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 65f264d1c98f61c4f9143ddeb0e74ff5
timeCreated: 1476961746
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,190 @@
namespace SRF.UI
{
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DragHandle : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{
private CanvasScaler _canvasScaler;
private float _delta;
private float _startValue;
public RectTransform.Axis Axis = RectTransform.Axis.Horizontal;
public bool Invert = false;
public float MaxSize = -1;
public LayoutElement TargetLayoutElement;
public RectTransform TargetRectTransform;
private float Mult
{
get { return Invert ? -1 : 1; }
}
public void OnBeginDrag(PointerEventData eventData)
{
if (!Verify())
{
return;
}
//Debug.Log("OnBeginDrag");
_startValue = GetCurrentValue();
_delta = 0;
}
public void OnDrag(PointerEventData eventData)
{
if (!Verify())
{
return;
}
//Debug.Log("OnDrag");
var delta = 0f;
if (Axis == RectTransform.Axis.Horizontal)
{
delta += eventData.delta.x;
}
else
{
delta += eventData.delta.y;
}
if (_canvasScaler != null)
{
delta /= _canvasScaler.scaleFactor;
}
delta *= Mult;
_delta += delta;
SetCurrentValue(Mathf.Clamp(_startValue + _delta, GetMinSize(), GetMaxSize()));
}
public void OnEndDrag(PointerEventData eventData)
{
if (!Verify())
{
return;
}
//Debug.Log("OnEndDrag");
SetCurrentValue(Mathf.Max(_startValue + _delta, GetMinSize()));
_delta = 0;
CommitCurrentValue();
}
private void Start()
{
Verify();
_canvasScaler = GetComponentInParent<CanvasScaler>();
}
private bool Verify()
{
if (TargetLayoutElement == null && TargetRectTransform == null)
{
Debug.LogWarning(
"DragHandle: TargetLayoutElement and TargetRectTransform are both null. Disabling behaviour.");
enabled = false;
return false;
}
return true;
}
private float GetCurrentValue()
{
if (TargetLayoutElement != null)
{
return Axis == RectTransform.Axis.Horizontal
? TargetLayoutElement.preferredWidth
: TargetLayoutElement.preferredHeight;
}
if (TargetRectTransform != null)
{
return Axis == RectTransform.Axis.Horizontal
? TargetRectTransform.sizeDelta.x
: TargetRectTransform.sizeDelta.y;
}
throw new InvalidOperationException();
}
private void SetCurrentValue(float value)
{
if (TargetLayoutElement != null)
{
if (Axis == RectTransform.Axis.Horizontal)
{
TargetLayoutElement.preferredWidth = value;
}
else
{
TargetLayoutElement.preferredHeight = value;
}
return;
}
if (TargetRectTransform != null)
{
var d = TargetRectTransform.sizeDelta;
if (Axis == RectTransform.Axis.Horizontal)
{
d.x = value;
}
else
{
d.y = value;
}
TargetRectTransform.sizeDelta = d;
return;
}
throw new InvalidOperationException();
}
private void CommitCurrentValue()
{
if (TargetLayoutElement != null)
{
if (Axis == RectTransform.Axis.Horizontal)
{
TargetLayoutElement.preferredWidth = ((RectTransform) TargetLayoutElement.transform).sizeDelta.x;
}
else
{
TargetLayoutElement.preferredHeight = ((RectTransform) TargetLayoutElement.transform).sizeDelta.y;
}
}
}
private float GetMinSize()
{
if (TargetLayoutElement == null)
{
return 0;
}
return Axis == RectTransform.Axis.Horizontal ? TargetLayoutElement.minWidth : TargetLayoutElement.minHeight;
}
private float GetMaxSize()
{
if (MaxSize > 0)
{
return MaxSize;
}
return float.MaxValue;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8faed27c04557e24e8aecd35f2b4d9d3
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,5 @@
fileFormatVersion: 2
guid: fee397aaceb8d684a94ce2bae9b71aa1
folderAsset: yes
DefaultImporter:
userData:

View File

@@ -0,0 +1,39 @@
namespace SRF.UI.Editor
{
/*[CustomEditor(typeof(CopyLayoutElement))]
[CanEditMultipleObjects]
public class CopyLayoutElementEditor : UnityEditor.Editor
{
private SerializedProperty _copySourceProperty;
private SerializedProperty _paddingWidthProperty;
private SerializedProperty _paddingHeightProperty;
protected void OnEnable()
{
_paddingWidthProperty = serializedObject.FindProperty("PaddingWidth");
_paddingHeightProperty = serializedObject.FindProperty("PaddingHeight");
_copySourceProperty = serializedObject.FindProperty("CopySource");
}
public override void OnInspectorGUI()
{
//base.OnInspectorGUI();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(_copySourceProperty);
EditorGUILayout.PropertyField(_paddingWidthProperty);
EditorGUILayout.PropertyField(_paddingHeightProperty);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
}
}*/
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 44df26ca5be5b5c468b5090cbe3df8ab
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,34 @@
using UnityEditor;
namespace SRF.UI.Editor
{
[CustomEditor(typeof (CopyPreferredSize))]
[CanEditMultipleObjects]
public class CopyPreferredSizeEditor : UnityEditor.Editor
{
private SerializedProperty _copySourceProperty;
private SerializedProperty _paddingHeightProperty;
private SerializedProperty _paddingWidthProperty;
protected void OnEnable()
{
_paddingWidthProperty = serializedObject.FindProperty("PaddingWidth");
_paddingHeightProperty = serializedObject.FindProperty("PaddingHeight");
_copySourceProperty = serializedObject.FindProperty("CopySource");
}
public override void OnInspectorGUI()
{
//base.OnInspectorGUI();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(_copySourceProperty);
EditorGUILayout.PropertyField(_paddingWidthProperty);
EditorGUILayout.PropertyField(_paddingHeightProperty);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 776c60ba14d0d0242968c3258a3ba16c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,31 @@
using UnityEditor;
namespace SRF.UI.Editor
{
[CustomEditor(typeof(CopyPreferredSizes))]
[CanEditMultipleObjects]
public class CopyPreferredSizesEditor : UnityEditor.Editor
{
private SerializedProperty _copySourcesProperty;
private SerializedProperty _operationProperty;
protected void OnEnable()
{
_copySourcesProperty = serializedObject.FindProperty("CopySources");
_operationProperty = serializedObject.FindProperty("Operation");
}
public override void OnInspectorGUI()
{
//base.OnInspectorGUI();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(_operationProperty);
EditorGUILayout.PropertyField(_copySourcesProperty);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
}
}
}

View File

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

View File

@@ -0,0 +1,28 @@
using UnityEditor;
using UnityEditor.UI;
namespace SRF.UI.Editor
{
[CustomEditor(typeof (LongPressButton), true)]
[CanEditMultipleObjects]
public class LongPressButtonEditor : ButtonEditor
{
private SerializedProperty _onLongPressProperty;
protected override void OnEnable()
{
base.OnEnable();
_onLongPressProperty = serializedObject.FindProperty("_onLongPress");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.Space();
serializedObject.Update();
EditorGUILayout.PropertyField(_onLongPressProperty);
serializedObject.ApplyModifiedProperties();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1d57f229ac662764aa4508a0d42ddede
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,32 @@
using UnityEditor;
using UnityEditor.UI;
namespace SRF.UI.Editor
{
[CustomEditor(typeof (SRNumberButton))]
[CanEditMultipleObjects]
public class SRNumberButtonEditor : ButtonEditor
{
private SerializedProperty _amountProperty;
private SerializedProperty _targetFieldProperty;
protected override void OnEnable()
{
base.OnEnable();
_targetFieldProperty = serializedObject.FindProperty("TargetField");
_amountProperty = serializedObject.FindProperty("Amount");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.Space();
serializedObject.Update();
EditorGUILayout.PropertyField(_targetFieldProperty);
EditorGUILayout.PropertyField(_amountProperty);
serializedObject.ApplyModifiedProperties();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0d1845f798a1b5a47af337e37e463641
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,10 @@
{
"name": "StompyRobot.SRF.Editor",
"references": [
"StompyRobot.SRF"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": []
}

View File

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

View File

@@ -0,0 +1,105 @@
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace SRF.UI.Editor
{
[CustomEditor(typeof (StyleComponent))]
[CanEditMultipleObjects]
public class StyleComponentEditor : UnityEditor.Editor
{
private SerializedProperty _styleKeyProperty;
protected void OnEnable()
{
_styleKeyProperty = serializedObject.FindProperty("_styleKey");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var styleComponent = serializedObject.targetObject as StyleComponent;
if (styleComponent == null)
{
Debug.LogWarning("Target is null, expected StyleComponent");
return;
}
var styleRoot = styleComponent.GetComponentInParent<StyleRoot>();
if (styleRoot == null)
{
EditorGUILayout.HelpBox("There must be a StyleRoot component above this object in the hierarchy.",
MessageType.Error,
true);
return;
}
var styleSheet = styleRoot.StyleSheet;
if (styleSheet == null)
{
EditorGUILayout.HelpBox("Style Root has no stylesheet set.", MessageType.Warning);
EditorGUILayout.Popup("Key", 0,
new[] {string.IsNullOrEmpty(styleComponent.StyleKey) ? "--" : styleComponent.StyleKey});
return;
}
var options = styleRoot.StyleSheet.GetStyleKeys(true).ToList();
var index = _styleKeyProperty.hasMultipleDifferentValues
? 0
: options.IndexOf(_styleKeyProperty.stringValue) + 1;
options.Insert(0, "--");
EditorGUILayout.Separator();
GUI.enabled = _styleKeyProperty.editable;
var newIndex = EditorGUILayout.Popup("Key", index, options.ToArray());
GUI.enabled = true;
if (newIndex != index)
{
_styleKeyProperty.stringValue = "";
_styleKeyProperty.stringValue = newIndex == 0 ? "" : options[newIndex];
}
if (serializedObject.ApplyModifiedProperties())
{
foreach (var o in serializedObject.targetObjects)
{
var c = o as StyleComponent;
c.Refresh(true);
}
_styleKeyProperty.serializedObject.Update();
}
EditorGUILayout.Separator();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Open StyleSheet"))
{
Selection.activeObject = styleRoot.StyleSheet;
}
EditorGUILayout.Separator();
if (GUILayout.Button("Select StyleRoot"))
{
Selection.activeGameObject = styleRoot.gameObject;
}
GUILayout.EndHorizontal();
EditorGUILayout.Separator();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ffea2a0fd78a7484f88b5b877c0d6659
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,178 @@
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace SRF.UI.Editor
{
[CustomEditor(typeof (StyleSheet))]
public class StyleSheetEditor : UnityEditor.Editor
{
public const float ColourColumnWidth = 40f;
public const float OverrideColumnWidth = 20f;
private string _newKeyField = "";
public override void OnInspectorGUI()
{
var styleSheet = target as StyleSheet;
if (styleSheet == null)
{
Debug.LogWarning("Expected target to be StyleSheer", target);
return;
}
var parentStyleSheet = styleSheet.Parent;
styleSheet.Parent =
EditorGUILayout.ObjectField("Parent", styleSheet.Parent, typeof (StyleSheet), false) as StyleSheet;
EditorGUILayout.Separator();
EditorGUILayout.Separator();
EditorGUILayout.BeginVertical();
// Draw table header
EditorGUILayout.BeginHorizontal();
GUILayout.Space(OverrideColumnWidth);
GUILayout.Label("Name");
GUILayout.Label("Img", GUILayout.Width(ColourColumnWidth));
GUILayout.Label("Norm.", GUILayout.Width(ColourColumnWidth));
GUILayout.Label("Hov.", GUILayout.Width(ColourColumnWidth));
GUILayout.Label("Actv.", GUILayout.Width(ColourColumnWidth));
GUILayout.Label("Dsbld.", GUILayout.Width(ColourColumnWidth));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
var keys = styleSheet.GetStyleKeys(false);
if (parentStyleSheet != null)
{
keys = keys.Union(parentStyleSheet.GetStyleKeys());
}
// Draw rows
foreach (var key in keys)
{
// Style from the current stylesheet
var style = styleSheet.GetStyle(key, false);
// Style from the parent stylesheet
Style parentStyle = null;
if (parentStyleSheet != null)
{
parentStyle = parentStyleSheet.GetStyle(key, true);
}
EditorGUILayout.BeginHorizontal();
var canEdit = style != null;
// If there is a parent stylesheet, and the parent contains this key
if (parentStyleSheet != null && parentStyle != null)
{
var overrideParent = GUILayout.Toggle(style != null, "", GUILayout.Width(OverrideColumnWidth));
if (overrideParent && style == null)
{
// Copy the style to the current stylesheet
Undo.RecordObject(styleSheet, "Override Style");
styleSheet.AddStyle(key);
style = styleSheet.GetStyle(key, false);
style.CopyFrom(parentStyle);
EditorUtility.SetDirty(styleSheet);
canEdit = true;
}
else if (!overrideParent && style != null)
{
Undo.RecordObject(styleSheet, "Delete Style");
styleSheet.DeleteStyle(key);
style = null;
EditorUtility.SetDirty(styleSheet);
canEdit = false;
}
}
else
{
// Otherwise display a delete button
if (GUILayout.Button("X", GUILayout.Width(OverrideColumnWidth)))
{
Undo.RecordObject(styleSheet, "Delete Style");
styleSheet.DeleteStyle(key);
EditorUtility.SetDirty(styleSheet);
continue;
}
}
GUI.enabled = canEdit;
GUILayout.Label(key);
EditorGUI.BeginChangeCheck();
var img =
EditorGUILayout.ObjectField(style != null ? style.Image : parentStyle.Image, typeof (Sprite), false,
GUILayout.Width(ColourColumnWidth)) as Sprite;
var normalColor = EditorGUILayout.ColorField(
style != null ? style.NormalColor : parentStyle.NormalColor,
GUILayout.Width(ColourColumnWidth));
var hoverColor = EditorGUILayout.ColorField(style != null ? style.HoverColor : parentStyle.HoverColor,
GUILayout.Width(ColourColumnWidth));
var activeColor = EditorGUILayout.ColorField(
style != null ? style.ActiveColor : parentStyle.ActiveColor,
GUILayout.Width(ColourColumnWidth));
var disabledColor =
EditorGUILayout.ColorField(style != null ? style.DisabledColor : parentStyle.DisabledColor,
GUILayout.Width(ColourColumnWidth));
if (EditorGUI.EndChangeCheck() && canEdit)
{
Undo.RecordObject(styleSheet, "Update Style");
style.Image = img;
style.NormalColor = normalColor;
style.HoverColor = hoverColor;
style.ActiveColor = activeColor;
style.DisabledColor = disabledColor;
EditorUtility.SetDirty(styleSheet);
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
GUILayout.Label("New Style");
_newKeyField = EditorGUILayout.TextField(_newKeyField);
GUI.enabled = !string.IsNullOrEmpty(_newKeyField) && styleSheet.GetStyle(_newKeyField) == null;
if (GUILayout.Button("Add"))
{
Undo.RecordObject(styleSheet, "Add Style");
styleSheet.AddStyle(_newKeyField);
EditorUtility.SetDirty(styleSheet);
_newKeyField = "";
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7cc490d54f84d704f90e31d72e293018
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,71 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// Instantly sets colour to FlashColor on pointer down, then fades back to DefaultColour once pointer is released.
/// </summary>
[AddComponentMenu(ComponentMenuPaths.FlashGraphic)]
[ExecuteInEditMode]
public class FlashGraphic : UIBehaviour, IPointerDownHandler, IPointerUpHandler
{
public float DecayTime = 0.15f;
public Color DefaultColor = new Color(1, 1, 1, 0);
public Color FlashColor = Color.white;
public Graphic Target;
private bool _isHoldingUntilNextPress;
public void OnPointerDown(PointerEventData eventData)
{
Target.CrossFadeColor(FlashColor, 0f, true, true);
_isHoldingUntilNextPress = false;
}
public void OnPointerUp(PointerEventData eventData)
{
if (!_isHoldingUntilNextPress)
{
Target.CrossFadeColor(DefaultColor, DecayTime, true, true);
}
}
protected override void OnEnable()
{
base.OnEnable();
if (!_isHoldingUntilNextPress)
{
Target.CrossFadeColor(DefaultColor, 0f, true, true);
}
}
#if UNITY_EDITOR
protected void Update()
{
if (!Application.isPlaying && Target != null)
{
Target.CrossFadeColor(DefaultColor, 0, true, true);
}
}
#endif
public void Flash()
{
Target.CrossFadeColor(FlashColor, 0f, true, true);
Target.CrossFadeColor(DefaultColor, DecayTime, true, true);
_isHoldingUntilNextPress = false;
}
public void FlashAndHoldUntilNextPress()
{
Target.CrossFadeColor(FlashColor, 0f, true, true);
_isHoldingUntilNextPress = true;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 95878e800ddd366418edfb56a22f9d56
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,48 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof (Graphic))]
[ExecuteInEditMode]
[AddComponentMenu(ComponentMenuPaths.InheritColour)]
public class InheritColour : SRMonoBehaviour
{
private Graphic _graphic;
public Graphic From;
private Graphic Graphic
{
get
{
if (_graphic == null)
{
_graphic = GetComponent<Graphic>();
}
return _graphic;
}
}
private void Refresh()
{
if (From == null)
{
return;
}
Graphic.color = From.canvasRenderer.GetColor();
}
private void Update()
{
Refresh();
}
private void Start()
{
Refresh();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5ed84aa42fb48c9458d3942c1d059055
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,5 @@
fileFormatVersion: 2
guid: e77c380334ccc0d438d07473a296a1cc
folderAsset: yes
DefaultImporter:
userData:

View File

@@ -0,0 +1,304 @@
namespace SRF.UI.Layout
{
using System.Collections.Generic;
using Internal;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Layout Group controller that arranges children in rows, fitting as many on a line until total width exceeds parent
/// bounds
/// </summary>
[AddComponentMenu(ComponentMenuPaths.FlowLayoutGroup)]
public class FlowLayoutGroup : LayoutGroup
{
/// <summary>
/// Holds the rects that will make up the current row being processed
/// </summary>
private readonly IList<RectTransform> _rowList = new List<RectTransform>();
private float _layoutHeight;
public bool ChildForceExpandHeight = false;
public bool ChildForceExpandWidth = false;
public float Spacing = 0f;
protected bool IsCenterAlign
{
get
{
return childAlignment == TextAnchor.LowerCenter || childAlignment == TextAnchor.MiddleCenter ||
childAlignment == TextAnchor.UpperCenter;
}
}
protected bool IsRightAlign
{
get
{
return childAlignment == TextAnchor.LowerRight || childAlignment == TextAnchor.MiddleRight ||
childAlignment == TextAnchor.UpperRight;
}
}
protected bool IsMiddleAlign
{
get
{
return childAlignment == TextAnchor.MiddleLeft || childAlignment == TextAnchor.MiddleRight ||
childAlignment == TextAnchor.MiddleCenter;
}
}
protected bool IsLowerAlign
{
get
{
return childAlignment == TextAnchor.LowerLeft || childAlignment == TextAnchor.LowerRight ||
childAlignment == TextAnchor.LowerCenter;
}
}
public override void CalculateLayoutInputHorizontal()
{
base.CalculateLayoutInputHorizontal();
var minWidth = GetGreatestMinimumChildWidth() + padding.left + padding.right;
SetLayoutInputForAxis(minWidth, -1, -1, 0);
}
public override void SetLayoutHorizontal()
{
SetLayout(rectTransform.rect.width, 0, false);
}
public override void SetLayoutVertical()
{
SetLayout(rectTransform.rect.width, 1, false);
}
public override void CalculateLayoutInputVertical()
{
_layoutHeight = SetLayout(rectTransform.rect.width, 1, true);
}
/// <summary>
/// Main layout method
/// </summary>
/// <param name="width">Width to calculate the layout with</param>
/// <param name="axis">0 for horizontal axis, 1 for vertical</param>
/// <param name="layoutInput">If true, sets the layout input for the axis. If false, sets child position for axis</param>
public float SetLayout(float width, int axis, bool layoutInput)
{
var groupHeight = rectTransform.rect.height;
// Width that is available after padding is subtracted
var workingWidth = rectTransform.rect.width - padding.left - padding.right;
// Accumulates the total height of the rows, including spacing and padding.
var yOffset = IsLowerAlign ? padding.bottom : (float)padding.top;
var currentRowWidth = 0f;
var currentRowHeight = 0f;
for (var i = 0; i < rectChildren.Count; i++)
{
// LowerAlign works from back to front
var index = IsLowerAlign ? rectChildren.Count - 1 - i : i;
var child = rectChildren[index];
var childWidth = LayoutUtility.GetPreferredSize(child, 0);
var childHeight = LayoutUtility.GetPreferredSize(child, 1);
// Max child width is layout group with - padding
childWidth = Mathf.Min(childWidth, workingWidth);
// Apply spacing if not the first element in a row
if (_rowList.Count > 0)
{
currentRowWidth += Spacing;
}
// If adding this element would exceed the bounds of the row,
// go to a new line after processing the current row
if (currentRowWidth + childWidth > workingWidth)
{
// Undo spacing addition if we're moving to a new line (Spacing is not applied on edges)
currentRowWidth -= Spacing;
// Process current row elements positioning
if (!layoutInput)
{
var h = CalculateRowVerticalOffset(groupHeight, yOffset, currentRowHeight);
LayoutRow(_rowList, currentRowWidth, currentRowHeight, workingWidth, padding.left, h, axis);
}
// Clear existing row
_rowList.Clear();
// Add the current row height to total height accumulator, and reset to 0 for the next row
yOffset += currentRowHeight;
yOffset += Spacing;
currentRowHeight = 0;
currentRowWidth = 0;
}
currentRowWidth += childWidth;
_rowList.Add(child);
// We need the largest element height to determine the starting position of the next line
if (childHeight > currentRowHeight)
{
currentRowHeight = childHeight;
}
}
if (!layoutInput)
{
var h = CalculateRowVerticalOffset(groupHeight, yOffset, currentRowHeight);
// Layout the final row
LayoutRow(_rowList, currentRowWidth, currentRowHeight, workingWidth, padding.left, h, axis);
}
_rowList.Clear();
// Add the last rows height to the height accumulator
yOffset += currentRowHeight;
yOffset += IsLowerAlign ? padding.top : padding.bottom;
if (layoutInput)
{
if (axis == 1)
{
SetLayoutInputForAxis(yOffset, yOffset, -1, axis);
}
}
return yOffset;
}
private float CalculateRowVerticalOffset(float groupHeight, float yOffset, float currentRowHeight)
{
float h;
if (IsLowerAlign)
{
h = groupHeight - yOffset - currentRowHeight;
}
else if (IsMiddleAlign)
{
h = groupHeight * 0.5f - _layoutHeight * 0.5f + yOffset;
}
else
{
h = yOffset;
}
return h;
}
protected void LayoutRow(IList<RectTransform> contents, float rowWidth, float rowHeight, float maxWidth,
float xOffset, float yOffset, int axis)
{
var xPos = xOffset;
if (!ChildForceExpandWidth && IsCenterAlign)
{
xPos += (maxWidth - rowWidth) * 0.5f;
}
else if (!ChildForceExpandWidth && IsRightAlign)
{
xPos += (maxWidth - rowWidth);
}
var extraWidth = 0f;
if (ChildForceExpandWidth)
{
var flexibleChildCount = 0;
for (var i = 0; i < _rowList.Count; i++)
{
if (LayoutUtility.GetFlexibleWidth(_rowList[i]) > 0f)
{
flexibleChildCount++;
}
}
if (flexibleChildCount > 0)
{
extraWidth = (maxWidth - rowWidth) / flexibleChildCount;
}
}
for (var j = 0; j < _rowList.Count; j++)
{
var index = IsLowerAlign ? _rowList.Count - 1 - j : j;
var rowChild = _rowList[index];
var rowChildWidth = LayoutUtility.GetPreferredSize(rowChild, 0);
if (LayoutUtility.GetFlexibleWidth(rowChild) > 0f)
{
rowChildWidth += extraWidth;
}
var rowChildHeight = LayoutUtility.GetPreferredSize(rowChild, 1);
if (ChildForceExpandHeight)
{
rowChildHeight = rowHeight;
}
rowChildWidth = Mathf.Min(rowChildWidth, maxWidth);
var yPos = yOffset;
if (IsMiddleAlign)
{
yPos += (rowHeight - rowChildHeight) * 0.5f;
}
else if (IsLowerAlign)
{
yPos += (rowHeight - rowChildHeight);
}
if (axis == 0)
{
#if UNITY_2019_1
SetChildAlongAxis(rowChild, 0, 1f, xPos, rowChildWidth);
#else
SetChildAlongAxis(rowChild, 0, xPos, rowChildWidth);
#endif
}
else
{
#if UNITY_2019_1
SetChildAlongAxis(rowChild, 1, 1f, yPos, rowChildHeight);
#else
SetChildAlongAxis(rowChild, 1, yPos, rowChildHeight);
#endif
}
xPos += rowChildWidth + Spacing;
}
}
public float GetGreatestMinimumChildWidth()
{
var max = 0f;
for (var i = 0; i < rectChildren.Count; i++)
{
var w = LayoutUtility.GetMinWidth(rectChildren[i]);
max = Mathf.Max(w, max);
}
return max;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f3a5149e46522d84cb8079537220a929
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,607 @@
//#define PROFILE
namespace SRF.UI.Layout
{
using System;
using Internal;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public interface IVirtualView
{
void SetDataContext(object data);
}
/// <summary>
/// </summary>
[AddComponentMenu(ComponentMenuPaths.VirtualVerticalLayoutGroup)]
public class VirtualVerticalLayoutGroup : LayoutGroup, IPointerClickHandler
{
private readonly SRList<object> _itemList = new SRList<object>();
private readonly SRList<int> _visibleItemList = new SRList<int>();
private bool _isDirty = false;
private SRList<Row> _rowCache = new SRList<Row>();
private ScrollRect _scrollRect;
private int _selectedIndex;
private object _selectedItem;
[SerializeField] private SelectedItemChangedEvent _selectedItemChanged;
private int _visibleItemCount;
private SRList<Row> _visibleRows = new SRList<Row>();
public StyleSheet AltRowStyleSheet;
public bool EnableSelection = true;
public RectTransform ItemPrefab;
/// <summary>
/// Rows to show above and below the visible rect to reduce pop-in
/// </summary>
public int RowPadding = 2;
public StyleSheet RowStyleSheet;
public StyleSheet SelectedRowStyleSheet;
/// <summary>
/// Spacing to add between rows
/// </summary>
public float Spacing;
/// <summary>
/// If true, the scroll view will stick to the last element when fully scrolled to the bottom and an item is added
/// </summary>
public bool StickToBottom = true;
public SelectedItemChangedEvent SelectedItemChanged
{
get { return _selectedItemChanged; }
set { _selectedItemChanged = value; }
}
public object SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem == value || !EnableSelection)
{
return;
}
var newSelectedIndex = value == null ? -1 : _itemList.IndexOf(value);
// Ensure that the new selected item is present in the item list
if (value != null && newSelectedIndex < 0)
{
throw new InvalidOperationException("Cannot select item not present in layout");
}
// Invalidate old selected item row
if (_selectedItem != null)
{
InvalidateItem(_selectedIndex);
}
_selectedItem = value;
_selectedIndex = newSelectedIndex;
// Invalidate the newly selected item
if (_selectedItem != null)
{
InvalidateItem(_selectedIndex);
}
SetDirty();
if (_selectedItemChanged != null)
{
_selectedItemChanged.Invoke(_selectedItem);
}
}
}
public override float minHeight
{
get { return _itemList.Count*ItemHeight + padding.top + padding.bottom + Spacing*_itemList.Count; }
}
public void OnPointerClick(PointerEventData eventData)
{
if (!EnableSelection)
{
return;
}
var hitObject = eventData.pointerPressRaycast.gameObject;
if (hitObject == null)
{
return;
}
var hitPos = hitObject.transform.position;
var localPos = rectTransform.InverseTransformPoint(hitPos);
var row = Mathf.FloorToInt(Mathf.Abs(localPos.y)/ItemHeight);
if (row >= 0 && row < _itemList.Count)
{
SelectedItem = _itemList[row];
}
else
{
SelectedItem = null;
}
}
protected override void Awake()
{
base.Awake();
ScrollRect.onValueChanged.AddListener(OnScrollRectValueChanged);
var view = ItemPrefab.GetComponent(typeof (IVirtualView));
if (view == null)
{
Debug.LogWarning(
"[VirtualVerticalLayoutGroup] ItemPrefab does not have a component inheriting from IVirtualView, so no data binding can occur");
}
}
private void OnScrollRectValueChanged(Vector2 d)
{
if (d.y < 0 || d.y > 1)
{
_scrollRect.verticalNormalizedPosition = Mathf.Clamp01(d.y);
}
//CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
SetDirty();
}
protected override void Start()
{
base.Start();
ScrollUpdate();
}
protected override void OnEnable()
{
base.OnEnable();
SetDirty();
}
protected void Update()
{
if (!AlignBottom && !AlignTop)
{
Debug.LogWarning("[VirtualVerticalLayoutGroup] Only Lower or Upper alignment is supported.", this);
childAlignment = TextAnchor.UpperLeft;
}
if (SelectedItem != null && !_itemList.Contains(SelectedItem))
{
SelectedItem = null;
}
if (_isDirty)
{
_isDirty = false;
ScrollUpdate();
}
}
/// <summary>
/// Invalidate a single row (before removing, or changing selection status)
/// </summary>
/// <param name="itemIndex"></param>
protected void InvalidateItem(int itemIndex)
{
if (!_visibleItemList.Contains(itemIndex))
{
return;
}
_visibleItemList.Remove(itemIndex);
for (var i = 0; i < _visibleRows.Count; i++)
{
if (_visibleRows[i].Index == itemIndex)
{
RecycleRow(_visibleRows[i]);
_visibleRows.RemoveAt(i);
break;
}
}
}
/// <summary>
/// After removing or inserting a row, ensure that the cached indexes (used for layout) match up
/// with the item index in the list
/// </summary>
protected void RefreshIndexCache()
{
for (var i = 0; i < _visibleRows.Count; i++)
{
_visibleRows[i].Index = _itemList.IndexOf(_visibleRows[i].Data);
}
}
protected void ScrollUpdate()
{
if (!Application.isPlaying)
{
return;
}
//Debug.Log("[SRConsole] ScrollUpdate {0}".Fmt(Time.frameCount));
var pos = rectTransform.anchoredPosition;
var startY = pos.y;
var viewHeight = ((RectTransform) ScrollRect.transform).rect.height;
// Determine the range of rows that should be visible
var rowRangeLower = Mathf.FloorToInt(startY/(ItemHeight + Spacing));
var rowRangeHigher = Mathf.CeilToInt((startY + viewHeight)/(ItemHeight + Spacing));
// Apply padding to reduce pop-in
rowRangeLower -= RowPadding;
rowRangeHigher += RowPadding;
rowRangeLower = Mathf.Max(0, rowRangeLower);
rowRangeHigher = Mathf.Min(_itemList.Count, rowRangeHigher);
var isDirty = false;
#if PROFILE
Profiler.BeginSample("Visible Rows Cull");
#endif
for (var i = 0; i < _visibleRows.Count; i++)
{
var row = _visibleRows[i];
// Move on if row is still visible
if (row.Index >= rowRangeLower && row.Index <= rowRangeHigher)
{
continue;
}
_visibleItemList.Remove(row.Index);
_visibleRows.Remove(row);
RecycleRow(row);
isDirty = true;
}
#if PROFILE
Profiler.EndSample();
Profiler.BeginSample("Item Visible Check");
#endif
for (var i = rowRangeLower; i < rowRangeHigher; ++i)
{
if (i >= _itemList.Count)
{
break;
}
// Move on if row is already visible
if (_visibleItemList.Contains(i))
{
continue;
}
var row = GetRow(i);
_visibleRows.Add(row);
_visibleItemList.Add(i);
isDirty = true;
}
#if PROFILE
Profiler.EndSample();
#endif
// If something visible has explicitly been changed, or the visible row count has changed
if (isDirty || _visibleItemCount != _visibleRows.Count)
{
//Debug.Log("[SRConsole] IsDirty {0}".Fmt(Time.frameCount));
LayoutRebuilder.MarkLayoutForRebuild(rectTransform);
}
_visibleItemCount = _visibleRows.Count;
}
public override void CalculateLayoutInputVertical()
{
SetLayoutInputForAxis(minHeight, minHeight, -1, 1);
}
public override void SetLayoutHorizontal()
{
var width = rectTransform.rect.width - padding.left - padding.right;
// Position visible rows at 0 x
for (var i = 0; i < _visibleRows.Count; i++)
{
var item = _visibleRows[i];
SetChildAlongAxis(item.Rect, 0, padding.left, width);
}
// Hide non-active rows to one side. More efficient than enabling/disabling them
for (var i = 0; i < _rowCache.Count; i++)
{
var item = _rowCache[i];
SetChildAlongAxis(item.Rect, 0, -width - padding.left, width);
}
}
public override void SetLayoutVertical()
{
if (!Application.isPlaying)
{
return;
}
//Debug.Log("[SRConsole] SetLayoutVertical {0}".Fmt(Time.frameCount));
// Position visible rows by the index of the item they represent
for (var i = 0; i < _visibleRows.Count; i++)
{
var item = _visibleRows[i];
SetChildAlongAxis(item.Rect, 1, item.Index*ItemHeight + padding.top + Spacing*item.Index, ItemHeight);
}
}
private new void SetDirty()
{
base.SetDirty();
if (!IsActive())
{
return;
}
_isDirty = true;
//CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
}
[Serializable]
public class SelectedItemChangedEvent : UnityEvent<object> {}
[Serializable]
private class Row
{
public object Data;
public int Index;
public RectTransform Rect;
public StyleRoot Root;
public IVirtualView View;
}
#region Public Data Methods
public void AddItem(object item)
{
_itemList.Add(item);
SetDirty();
if (StickToBottom && Mathf.Approximately(ScrollRect.verticalNormalizedPosition, 0f))
{
ScrollRect.normalizedPosition = new Vector2(0, 0);
}
}
public void RemoveItem(object item)
{
if (SelectedItem == item)
{
SelectedItem = null;
}
var index = _itemList.IndexOf(item);
InvalidateItem(index);
_itemList.Remove(item);
RefreshIndexCache();
SetDirty();
}
public void ClearItems()
{
for (var i = _visibleRows.Count - 1; i >= 0; i--)
{
InvalidateItem(_visibleRows[i].Index);
}
_itemList.Clear();
SetDirty();
}
#endregion
#region Internal Properties
private ScrollRect ScrollRect
{
get
{
if (_scrollRect == null)
{
_scrollRect = GetComponentInParent<ScrollRect>();
}
return _scrollRect;
}
}
private bool AlignBottom
{
get
{
return childAlignment == TextAnchor.LowerRight || childAlignment == TextAnchor.LowerCenter ||
childAlignment == TextAnchor.LowerLeft;
}
}
private bool AlignTop
{
get
{
return childAlignment == TextAnchor.UpperLeft || childAlignment == TextAnchor.UpperCenter ||
childAlignment == TextAnchor.UpperRight;
}
}
private float _itemHeight = -1;
private float ItemHeight
{
get
{
if (_itemHeight <= 0)
{
var layoutElement = ItemPrefab.GetComponent(typeof (ILayoutElement)) as ILayoutElement;
if (layoutElement != null)
{
_itemHeight = layoutElement.preferredHeight;
}
else
{
_itemHeight = ItemPrefab.rect.height;
}
if (_itemHeight.ApproxZero())
{
Debug.LogWarning(
"[VirtualVerticalLayoutGroup] ItemPrefab must have a preferred size greater than 0");
_itemHeight = 10;
}
}
return _itemHeight;
}
}
#endregion
#region Row Pooling and Provisioning
private Row GetRow(int forIndex)
{
// If there are no rows available in the cache, create one from scratch
if (_rowCache.Count == 0)
{
var newRow = CreateRow();
PopulateRow(forIndex, newRow);
return newRow;
}
var data = _itemList[forIndex];
Row row = null;
Row altRow = null;
// Determine if the row we're looking for is an alt row
var target = forIndex%2;
// Try and find a row which previously had this data, so we can reuse it
for (var i = 0; i < _rowCache.Count; i++)
{
row = _rowCache[i];
// If this row previously represented this data, just use that one.
if (row.Data == data)
{
_rowCache.RemoveAt(i);
PopulateRow(forIndex, row);
break;
}
// Cache a row which is was the same alt state as the row we're looking for, in case
// we don't find an exact match.
if (row.Index%2 == target)
{
altRow = row;
}
// Didn't match, reset to null
row = null;
}
// If an exact match wasn't found, but a row with the same alt-status was found, use that one.
if (row == null && altRow != null)
{
_rowCache.Remove(altRow);
row = altRow;
PopulateRow(forIndex, row);
}
else if (row == null)
{
// No match found, use the last added item in the cache
row = _rowCache.PopLast();
PopulateRow(forIndex, row);
}
return row;
}
private void RecycleRow(Row row)
{
_rowCache.Add(row);
}
private void PopulateRow(int index, Row row)
{
row.Index = index;
// Set data context on row
row.Data = _itemList[index];
row.View.SetDataContext(_itemList[index]);
// If we're using stylesheets
if (RowStyleSheet != null || AltRowStyleSheet != null || SelectedRowStyleSheet != null)
{
// If there is a selected row stylesheet, and this is the selected row, use that one
if (SelectedRowStyleSheet != null && SelectedItem == row.Data)
{
row.Root.StyleSheet = SelectedRowStyleSheet;
}
else
{
// Otherwise just use the stylesheet suitable for the row alt-status
row.Root.StyleSheet = index%2 == 0 ? RowStyleSheet : AltRowStyleSheet;
}
}
}
private Row CreateRow()
{
var item = new Row();
var row = SRInstantiate.Instantiate(ItemPrefab);
item.Rect = row;
item.View = row.GetComponent(typeof (IVirtualView)) as IVirtualView;
if (RowStyleSheet != null || AltRowStyleSheet != null || SelectedRowStyleSheet != null)
{
item.Root = row.gameObject.GetComponentOrAdd<StyleRoot>();
item.Root.StyleSheet = RowStyleSheet;
}
row.SetParent(rectTransform, false);
return item;
}
#endregion
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 19c408e3f064e184fa5e0d9862ac4d8b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,74 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
[AddComponentMenu(ComponentMenuPaths.LongPressButton)]
public class LongPressButton : UnityEngine.UI.Button
{
private bool _handled;
[SerializeField] private ButtonClickedEvent _onLongPress = new ButtonClickedEvent();
private bool _pressed;
private float _pressedTime;
public float LongPressDuration = 0.9f;
public ButtonClickedEvent onLongPress
{
get { return _onLongPress; }
set { _onLongPress = value; }
}
public override void OnPointerExit(UnityEngine.EventSystems.PointerEventData eventData)
{
base.OnPointerExit(eventData);
_pressed = false;
}
public override void OnPointerDown(UnityEngine.EventSystems.PointerEventData eventData)
{
base.OnPointerDown(eventData);
if (eventData.button != UnityEngine.EventSystems.PointerEventData.InputButton.Left)
{
return;
}
_pressed = true;
_handled = false;
_pressedTime = Time.realtimeSinceStartup;
}
public override void OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData)
{
if (!_handled)
{
base.OnPointerUp(eventData);
}
_pressed = false;
}
public override void OnPointerClick(UnityEngine.EventSystems.PointerEventData eventData)
{
if (!_handled)
{
base.OnPointerClick(eventData);
}
}
private void Update()
{
if (!_pressed)
{
return;
}
if (Time.realtimeSinceStartup - _pressedTime >= LongPressDuration)
{
_pressed = false;
_handled = true;
onLongPress.Invoke();
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3fc6d8b69639fdc45a849df5b853c783
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,55 @@
namespace SRF.UI
{
using UnityEngine;
[ExecuteInEditMode]
[RequireComponent(typeof (RectTransform))]
public abstract class ResponsiveBase : SRMonoBehaviour
{
private bool _queueRefresh;
protected RectTransform RectTransform
{
get { return (RectTransform) CachedTransform; }
}
protected void OnEnable()
{
_queueRefresh = true;
}
protected void OnRectTransformDimensionsChange()
{
_queueRefresh = true;
}
protected void Update()
{
#if UNITY_EDITOR
// Refresh whenever we can in the editor, since layout has quirky update behaviour
// when not in play mode
if (!Application.isPlaying)
{
Refresh();
return;
}
#endif
if (_queueRefresh)
{
Refresh();
_queueRefresh = false;
}
}
protected abstract void Refresh();
[ContextMenu("Refresh")]
private void DoRefresh()
{
Refresh();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8a53d43b4191c4c4d9ed43860feca27e
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,102 @@
namespace SRF.UI
{
using System;
using Internal;
using UnityEngine;
[ExecuteInEditMode]
[RequireComponent(typeof (RectTransform))]
[AddComponentMenu(ComponentMenuPaths.ResponsiveEnable)]
public class ResponsiveEnable : ResponsiveBase
{
public enum Modes
{
EnableAbove,
EnableBelow
}
public Entry[] Entries = new Entry[0];
protected override void Refresh()
{
var rect = RectTransform.rect;
for (var i = 0; i < Entries.Length; i++)
{
var e = Entries[i];
var enable = true;
switch (e.Mode)
{
case Modes.EnableAbove:
{
if (e.ThresholdHeight > 0)
{
enable = rect.height >= e.ThresholdHeight && enable;
}
if (e.ThresholdWidth > 0)
{
enable = rect.width >= e.ThresholdWidth && enable;
}
break;
}
case Modes.EnableBelow:
{
if (e.ThresholdHeight > 0)
{
enable = rect.height <= e.ThresholdHeight && enable;
}
if (e.ThresholdWidth > 0)
{
enable = rect.width <= e.ThresholdWidth && enable;
}
break;
}
default:
throw new IndexOutOfRangeException();
}
if (e.GameObjects != null)
{
for (var j = 0; j < e.GameObjects.Length; j++)
{
var go = e.GameObjects[j];
if (go != null)
{
go.SetActive(enable);
}
}
}
if (e.Components != null)
{
for (var j = 0; j < e.Components.Length; j++)
{
var go = e.Components[j];
if (go != null)
{
go.enabled = enable;
}
}
}
}
}
[Serializable]
public struct Entry
{
public Behaviour[] Components;
public GameObject[] GameObjects;
public Modes Mode;
public float ThresholdHeight;
public float ThresholdWidth;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2415a15c0c9eea041863fc6c1a434ede
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,77 @@
namespace SRF.UI
{
using System;
using Internal;
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
[RequireComponent(typeof (RectTransform))]
[AddComponentMenu(ComponentMenuPaths.ResponsiveResize)]
public class ResponsiveResize : ResponsiveBase
{
public Element[] Elements = new Element[0];
protected override void Refresh()
{
var rect = RectTransform.rect;
for (var i = 0; i < Elements.Length; i++)
{
var e = Elements[i];
if (e.Target == null)
{
continue;
}
var maxWidth = float.MinValue;
var selectedWidth = -1f;
for (var j = 0; j < e.SizeDefinitions.Length; j++)
{
var d = e.SizeDefinitions[j];
// If the threshold applies
if (d.ThresholdWidth <= rect.width)
{
// And it is the largest width so far
if (d.ThresholdWidth > maxWidth)
{
// Set it as active
maxWidth = d.ThresholdWidth;
selectedWidth = d.ElementWidth;
}
}
}
if (selectedWidth > 0)
{
e.Target.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, selectedWidth);
var le = e.Target.GetComponent<LayoutElement>();
if (le != null)
{
le.preferredWidth = selectedWidth;
}
}
}
}
[Serializable]
public struct Element
{
public SizeDefinition[] SizeDefinitions;
public RectTransform Target;
[Serializable]
public struct SizeDefinition
{
[Tooltip("Width to apply when over the threshold width")] public float ElementWidth;
[Tooltip("Threshold over which this width will take effect")] public float ThresholdWidth;
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 395e9c70b6db8df408e038114524cc0b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,83 @@
using UnityEngine.UI;
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.EventSystems;
[AddComponentMenu(ComponentMenuPaths.NumberButton)]
public class SRNumberButton : UnityEngine.UI.Button, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler
{
private const float ExtraThreshold = 3f;
public const float Delay = 0.4f;
private float _delayTime;
private float _downTime;
private bool _isDown;
public double Amount = 1;
public SRNumberSpinner TargetField;
public override void OnPointerDown(PointerEventData eventData)
{
base.OnPointerDown(eventData);
if (!interactable)
{
return;
}
Apply();
_isDown = true;
_downTime = Time.realtimeSinceStartup;
_delayTime = _downTime + Delay;
}
public override void OnPointerUp(PointerEventData eventData)
{
base.OnPointerUp(eventData);
_isDown = false;
}
protected virtual void Update()
{
if (_isDown)
{
if (_delayTime <= Time.realtimeSinceStartup)
{
Apply();
var newDelay = Delay*0.5f;
var extra = Mathf.RoundToInt((Time.realtimeSinceStartup - _downTime)/ExtraThreshold);
for (var i = 0; i < extra; i++)
{
newDelay *= 0.5f;
}
_delayTime = Time.realtimeSinceStartup + newDelay;
}
}
}
private void Apply()
{
var currentValue = double.Parse(TargetField.text);
currentValue += Amount;
if (currentValue > TargetField.MaxValue)
{
currentValue = TargetField.MaxValue;
}
if (currentValue < TargetField.MinValue)
{
currentValue = TargetField.MinValue;
}
TargetField.text = currentValue.ToString();
TargetField.onEndEdit.Invoke(TargetField.text);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e271d820ea3d50a40bd29c81c23cb2a1
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,176 @@
namespace SRF.UI
{
using System;
using Internal;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[AddComponentMenu(ComponentMenuPaths.NumberSpinner)]
public class SRNumberSpinner : InputField
{
private double _currentValue;
private double _dragStartAmount;
private double _dragStep;
public float DragSensitivity = 0.01f;
public double MaxValue = double.MaxValue;
public double MinValue = double.MinValue;
protected override void Awake()
{
base.Awake();
if (contentType != ContentType.IntegerNumber && contentType != ContentType.DecimalNumber)
{
Debug.LogError("[SRNumberSpinner] contentType must be integer or decimal. Defaulting to integer");
contentType = ContentType.DecimalNumber;
}
}
public override void OnPointerClick(PointerEventData eventData)
{
//Debug.Log("OnPointerClick (isFocused: {0}, isUsed: {1}, isDragging: {2})".Fmt(isFocused, eventData.used, eventData.dragging));
if (!interactable)
{
return;
}
if (eventData.dragging)
{
return;
}
EventSystem.current.SetSelectedGameObject(gameObject, eventData);
base.OnPointerClick(eventData);
if ((m_Keyboard == null || !m_Keyboard.active))
{
OnSelect(eventData);
}
else
{
UpdateLabel();
eventData.Use();
}
}
public override void OnPointerDown(PointerEventData eventData)
{
//Debug.Log("OnPointerDown (isFocused: {0}, isUsed: {1})".Fmt(isFocused, eventData.used));
//base.OnPointerDown(eventData);
}
public override void OnPointerUp(PointerEventData eventData)
{
//Debug.Log("OnPointerUp (isFocused: {0}, isUsed: {1})".Fmt(isFocused, eventData.used));
//base.OnPointerUp(eventData);
}
public override void OnBeginDrag(PointerEventData eventData)
{
if (!interactable)
{
return;
}
//Debug.Log("OnBeginDrag (isFocused: {0}, isUsed: {1}, delta: {2})".Fmt(isFocused, eventData.used, eventData.delta));
// Pass event to parent if it is a vertical drag
if (Mathf.Abs(eventData.delta.y) > Mathf.Abs(eventData.delta.x))
{
//Debug.Log("Passing To Parent");
var parent = transform.parent;
if (parent != null)
{
eventData.pointerDrag = ExecuteEvents.GetEventHandler<IBeginDragHandler>(parent.gameObject);
if (eventData.pointerDrag != null)
{
ExecuteEvents.Execute(eventData.pointerDrag, eventData, ExecuteEvents.beginDragHandler);
}
}
return;
}
eventData.Use();
_dragStartAmount = double.Parse(text);
_currentValue = _dragStartAmount;
var minStep = 1f;
// Use a larger minimum step for integer numbers, since there are no fractional values
if (contentType == ContentType.IntegerNumber)
{
minStep *= 10;
}
_dragStep = Math.Max(minStep, _dragStartAmount*0.05f);
if (isFocused)
{
DeactivateInputField();
}
}
public override void OnDrag(PointerEventData eventData)
{
if (!interactable)
{
return;
}
//Debug.Log("OnDrag (isFocused: {0}, isUsed: {1})".Fmt(isFocused, eventData.used));
var diff = eventData.delta.x;
_currentValue += Math.Abs(_dragStep)*diff*DragSensitivity;
_currentValue = Math.Round(_currentValue, 2);
if (_currentValue > MaxValue)
{
_currentValue = MaxValue;
}
if (_currentValue < MinValue)
{
_currentValue = MinValue;
}
if (contentType == ContentType.IntegerNumber)
{
text = ((int) Math.Round(_currentValue)).ToString();
}
else
{
text = _currentValue.ToString();
}
}
public override void OnEndDrag(PointerEventData eventData)
{
if (!interactable)
{
return;
}
//Debug.Log("OnEndDrag (isFocused: {0}, isUsed: {1})".Fmt(isFocused, eventData.used));
//base.OnEndDrag(eventData);
eventData.Use();
if (_dragStartAmount != _currentValue)
{
DeactivateInputField();
SendOnSubmit();
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f7e6a39da209c144797f44248b82bfb3
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,68 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Detects when a screen dpi exceeds what the developer considers
/// a "retina" level display, and scales the canvas accordingly.
/// </summary>
[RequireComponent(typeof (CanvasScaler))]
[AddComponentMenu(ComponentMenuPaths.RetinaScaler)]
public class SRRetinaScaler : SRMonoBehaviour
{
[SerializeField] private bool _disablePixelPerfect = false;
[SerializeField] private int _designDpi = 120;
private void Start()
{
ApplyScaling();
}
private void ApplyScaling()
{
var dpi = Screen.dpi;
_lastDpi = dpi;
if (dpi <= 0)
{
return;
}
#if !UNITY_EDITOR && UNITY_IOS
// No iOS device has had low dpi for many years - Unity must be reporting it wrong.
if(dpi < 120)
{
dpi = 321;
}
#endif
var scaler = GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ConstantPixelSize;
// Round scale to nearest 0.5
float scale = dpi / _designDpi;
scale = Mathf.Max(1, Mathf.Round(scale * 2) / 2.0f);
scaler.scaleFactor = scale;
if (_disablePixelPerfect)
{
GetComponent<Canvas>().pixelPerfect = false;
}
}
private float _lastDpi;
void Update()
{
if (Screen.dpi != _lastDpi)
{
ApplyScaling();
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 58bc4004a23c662408dd40e6d01ac936
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,87 @@
namespace SRF.UI
{
using System;
using Internal;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[AddComponentMenu(ComponentMenuPaths.SRSpinner)]
public class SRSpinner : Selectable, IDragHandler, IBeginDragHandler
{
private float _dragDelta;
[SerializeField] private SpinEvent _onSpinDecrement = new SpinEvent();
[SerializeField] private SpinEvent _onSpinIncrement = new SpinEvent();
/// <summary>
/// Number of units a drag must accumulate to trigger a change
/// </summary>
public float DragThreshold = 20f;
public SpinEvent OnSpinIncrement
{
get { return _onSpinIncrement; }
set { _onSpinIncrement = value; }
}
public SpinEvent OnSpinDecrement
{
get { return _onSpinDecrement; }
set { _onSpinDecrement = value; }
}
public void OnBeginDrag(PointerEventData eventData)
{
_dragDelta = 0;
}
public void OnDrag(PointerEventData eventData)
{
if (!interactable)
{
return;
}
_dragDelta += eventData.delta.x;
if (Mathf.Abs(_dragDelta) > DragThreshold)
{
var direction = Mathf.Sign(_dragDelta);
var quantity = Mathf.FloorToInt(Mathf.Abs(_dragDelta)/DragThreshold);
if (direction > 0)
{
OnIncrement(quantity);
}
else
{
OnDecrement(quantity);
}
_dragDelta -= quantity*DragThreshold*direction;
}
}
private void OnIncrement(int amount)
{
for (var i = 0; i < amount; i++)
{
OnSpinIncrement.Invoke();
}
}
private void OnDecrement(int amount)
{
for (var i = 0; i < amount; i++)
{
OnSpinDecrement.Invoke();
}
}
[Serializable]
public class SpinEvent : UnityEvent {}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0b9fa4d99839aa940b36addec78cb92f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,26 @@
namespace SRF.UI
{
using System;
using Internal;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Adds a LayoutDirty callback to the default Text component.
/// </summary>
[AddComponentMenu(ComponentMenuPaths.SRText)]
public class SRText : Text
{
public event Action<SRText> LayoutDirty;
public override void SetLayoutDirty()
{
base.SetLayoutDirty();
if (LayoutDirty != null)
{
LayoutDirty(this);
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 983b04ffc0cd0a04fb74c9b74eb789bd
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,98 @@
namespace SRF.UI
{
using System;
using Internal;
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
[AddComponentMenu(ComponentMenuPaths.ScrollToBottom)]
public class ScrollToBottomBehaviour : MonoBehaviour
{
#pragma warning disable 649
[SerializeField]
private ScrollRect _scrollRect;
[SerializeField]
private CanvasGroup _canvasGroup;
[SerializeField]
private bool _scrollToTop;
#pragma warning restore 649
public void Start()
{
if (_scrollRect == null)
{
Debug.LogError("[ScrollToBottomBehaviour] ScrollRect not set");
return;
}
if (_canvasGroup == null)
{
Debug.LogError("[ScrollToBottomBehaviour] CanvasGroup not set");
return;
}
_scrollRect.onValueChanged.AddListener(OnScrollRectValueChanged);
Refresh();
}
void OnEnable()
{
Refresh();
}
public void Trigger()
{
if (_scrollToTop)
{
_scrollRect.normalizedPosition = new Vector2(0, 1);
}
else
{
_scrollRect.normalizedPosition = new Vector2(0, 0);
}
}
private void OnScrollRectValueChanged(Vector2 position)
{
Refresh();
}
private void Refresh()
{
if (_scrollRect == null)
return;
var position = _scrollRect.normalizedPosition;
if (position.y < 0.001f || (_scrollToTop && position.y >= 0.999f))
{
SetVisible(false);
}
else
{
SetVisible(true);
}
}
void SetVisible(bool truth)
{
if (truth)
{
_canvasGroup.alpha = 1f;
_canvasGroup.interactable = true;
_canvasGroup.blocksRaycasts = true;
}
else
{
_canvasGroup.alpha = 0f;
_canvasGroup.interactable = false;
_canvasGroup.blocksRaycasts = false;
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 35107bb7a2a89b54bbb85ea8ff193788
timeCreated: 1476980356
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,195 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;
[ExecuteInEditMode]
[AddComponentMenu(ComponentMenuPaths.StyleComponent)]
public class StyleComponent : SRMonoBehaviour
{
private Style _activeStyle;
private StyleRoot _cachedRoot;
private Graphic _graphic;
private bool _hasStarted;
private Image _image;
private Selectable _selectable;
[SerializeField] [FormerlySerializedAs("StyleKey")] [HideInInspector] private string _styleKey;
public bool IgnoreImage = false;
public string StyleKey
{
get { return _styleKey; }
set
{
_styleKey = value;
Refresh(false);
}
}
private void Start()
{
Refresh(true);
_hasStarted = true;
}
private void OnEnable()
{
if (_hasStarted)
{
Refresh(false);
}
}
#if UNITY_EDITOR
/// <summary>
/// This method is not included in exported builds - don't worry about it showing up in the profiler.
/// </summary>
private void Update()
{
if (!Application.isPlaying)
{
ApplyStyle();
}
}
#endif
public void Refresh(bool invalidateCache)
{
if (string.IsNullOrEmpty(StyleKey))
{
_activeStyle = null;
return;
}
if (!isActiveAndEnabled)
{
_cachedRoot = null;
return;
}
if (_cachedRoot == null || invalidateCache)
{
_cachedRoot = GetStyleRoot();
}
if (_cachedRoot == null)
{
Debug.LogWarning("[StyleComponent] No active StyleRoot object found in parents.", this);
_activeStyle = null;
return;
}
var s = _cachedRoot.GetStyle(StyleKey);
if (s == null)
{
Debug.LogWarning("[StyleComponent] Style not found ({0})".Fmt(StyleKey), this);
_activeStyle = null;
return;
}
_activeStyle = s;
ApplyStyle();
}
/// <summary>
/// Find the nearest enable style root component in parents
/// </summary>
/// <returns></returns>
private StyleRoot GetStyleRoot()
{
var t = CachedTransform;
StyleRoot root;
var i = 0;
do
{
root = t.GetComponentInParent<StyleRoot>();
if (root != null)
{
t = root.transform.parent;
}
++i;
if (i > 100)
{
Debug.LogWarning("Breaking Loop");
break;
}
} while ((root != null && !root.enabled) && t != null);
return root;
}
private void ApplyStyle()
{
if (_activeStyle == null)
{
return;
}
if (_graphic == null)
{
_graphic = GetComponent<Graphic>();
}
if (_selectable == null)
{
_selectable = GetComponent<Selectable>();
}
if (_image == null)
{
_image = GetComponent<Image>();
}
if (!IgnoreImage && _image != null)
{
_image.sprite = _activeStyle.Image;
}
if (_selectable != null)
{
var colours = _selectable.colors;
colours.normalColor = _activeStyle.NormalColor;
colours.highlightedColor = _activeStyle.HoverColor;
colours.pressedColor = _activeStyle.ActiveColor;
colours.disabledColor = _activeStyle.DisabledColor;
colours.colorMultiplier = 1f;
_selectable.colors = colours;
if (_graphic != null)
{
_graphic.color = Color.white;
}
}
else if (_graphic != null)
{
_graphic.color = _activeStyle.NormalColor;
}
}
private void SRStyleDirty()
{
// If inactive, invalidate the cached root and return. Next time it is enabled
// a new root will be found
if (!CachedGameObject.activeInHierarchy)
{
_cachedRoot = null;
return;
}
Refresh(true);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 73ae1b6eac706814a9cd427288a3c5c9
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,59 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
[ExecuteInEditMode]
[AddComponentMenu(ComponentMenuPaths.StyleRoot)]
public sealed class StyleRoot : SRMonoBehaviour
{
private StyleSheet _activeStyleSheet;
public StyleSheet StyleSheet;
public Style GetStyle(string key)
{
if (StyleSheet == null)
{
Debug.LogWarning("[StyleRoot] StyleSheet is not set.", this);
return null;
}
return StyleSheet.GetStyle(key);
}
private void OnEnable()
{
_activeStyleSheet = null;
if (StyleSheet != null)
{
OnStyleSheetChanged();
}
}
private void OnDisable()
{
OnStyleSheetChanged();
}
private void Update()
{
if (_activeStyleSheet != StyleSheet)
{
OnStyleSheetChanged();
}
}
private void OnStyleSheetChanged()
{
_activeStyleSheet = StyleSheet;
BroadcastMessage("SRStyleDirty", SendMessageOptions.DontRequireReceiver);
}
public void SetDirty()
{
_activeStyleSheet = null;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d1bf029da478aff42a6d6e0ed8e21203
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,110 @@
namespace SRF.UI
{
using System;
using System.Collections.Generic;
using System.Linq;
using Helpers;
using UnityEngine;
[Serializable]
public class Style
{
public Color ActiveColor = Color.white;
public Color DisabledColor = Color.white;
public Color HoverColor = Color.white;
public Sprite Image;
public Color NormalColor = Color.white;
public Style Copy()
{
var s = new Style();
s.CopyFrom(this);
return s;
}
public void CopyFrom(Style style)
{
Image = style.Image;
NormalColor = style.NormalColor;
HoverColor = style.HoverColor;
ActiveColor = style.ActiveColor;
DisabledColor = style.DisabledColor;
}
}
[Serializable]
public class StyleSheet : ScriptableObject
{
[SerializeField] private List<string> _keys = new List<string>();
[SerializeField] private List<Style> _styles = new List<Style>();
[SerializeField] public StyleSheet Parent;
public Style GetStyle(string key, bool searchParent = true)
{
var i = _keys.IndexOf(key);
if (i < 0)
{
if (searchParent && Parent != null)
{
return Parent.GetStyle(key);
}
return null;
}
return _styles[i];
}
#if UNITY_EDITOR
public int AddStyle(string key)
{
if (_keys.Contains(key))
{
throw new ArgumentException("key already exists");
}
_keys.Add(key);
_styles.Add(new Style());
return _keys.Count - 1;
}
public bool DeleteStyle(string key)
{
var i = _keys.IndexOf(key);
if (i < 0)
{
return false;
}
_keys.RemoveAt(i);
_styles.RemoveAt(i);
return true;
}
public IEnumerable<string> GetStyleKeys(bool includeParent = true)
{
if (Parent != null && includeParent)
{
return _keys.Union(Parent.GetStyleKeys());
}
return _keys.ToList();
}
[UnityEditor.MenuItem("Assets/Create/SRF/Style Sheet")]
public static void CreateStyleSheet()
{
var o = AssetUtil.CreateAsset<StyleSheet>();
AssetUtil.SelectAssetInProjectView(o);
}
#endif
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d631692ab5174474eaaf2b43947b0b9f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,35 @@
namespace SRF.UI
{
using Internal;
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// Do not allow an object to become select (automatically unfocus when receiving selection callback)
/// </summary>
[AddComponentMenu(ComponentMenuPaths.Unselectable)]
public sealed class Unselectable : SRMonoBehaviour, ISelectHandler
{
private bool _suspectedSelected;
public void OnSelect(BaseEventData eventData)
{
_suspectedSelected = true;
}
private void Update()
{
if (!_suspectedSelected)
{
return;
}
if (EventSystem.current.currentSelectedGameObject == CachedGameObject)
{
EventSystem.current.SetSelectedGameObject(null);
}
_suspectedSelected = false;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7134149b092993149867a9ce13a5ec50
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: