Scripts unified.

Initial editor options created, need some refinement.

--HG--
branch : develop
pull/413/head
Simon (darkside) Jackson 2015-02-02 23:07:31 +00:00
parent a297f0d599
commit e2aee6c02b
63 changed files with 4163 additions and 3700 deletions

4
README.md.meta Normal file
View File

@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: a7b682f292cfba6438971b2bc7e90705
DefaultImporter:
userData:

5
Scripts.meta Normal file
View File

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

5
Scripts/Accordion.meta Normal file
View File

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

View File

@ -1,13 +1,13 @@
///Credit ChoMPHi ///Credit ChoMPHi
///Sourced from - http://forum.unity3d.com/threads/accordion-type-layout.271818/ ///Sourced from - http://forum.unity3d.com/threads/accordion-type-layout.271818/
using UnityEngine;
using System.Collections;
namespace UnityEngine.UI namespace UnityEngine.UI.Extensions
{ {
[RequireComponent(typeof(VerticalLayoutGroup)), RequireComponent(typeof(ContentSizeFitter)), RequireComponent(typeof(ToggleGroup))] [RequireComponent(typeof(VerticalLayoutGroup), typeof(ContentSizeFitter), typeof(ToggleGroup))]
public class UIAccordion : MonoBehaviour { [AddComponentMenu("UI/Extensions/Accordion/Accordion Group")]
public class Accordion : MonoBehaviour
{
public enum Transition public enum Transition
{ {

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: c77f1d511e8ee4445a42bc41d95bb11f guid: 4387cc9950f37044c92f9d144a2b1002
MonoImporter: MonoImporter:
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []

View File

@ -1,27 +1,26 @@
///Credit ChoMPHi ///Credit ChoMPHi
///Sourced from - http://forum.unity3d.com/threads/accordion-type-layout.271818/ ///Sourced from - http://forum.unity3d.com/threads/accordion-type-layout.271818/
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI.Tweens;
using System; using System;
using System.Collections; using UnityEngine.UI.Extensions.Tweens;
namespace UnityEngine.UI namespace UnityEngine.UI.Extensions
{ {
[RequireComponent(typeof(RectTransform)), RequireComponent(typeof(LayoutElement))] [RequireComponent(typeof(RectTransform), typeof(LayoutElement))]
public class UIAccordionElement : Toggle { [AddComponentMenu("UI/Extensions/Accordion/Accordion Element")]
public class AccordionElement : Toggle
{
[SerializeField] private float m_MinHeight = 18f; [SerializeField] private float m_MinHeight = 18f;
private UIAccordion m_Accordion; private Accordion m_Accordion;
private RectTransform m_RectTransform; private RectTransform m_RectTransform;
private LayoutElement m_LayoutElement; private LayoutElement m_LayoutElement;
[NonSerialized] [NonSerialized]
private readonly TweenRunner<FloatTween> m_FloatTweenRunner; private readonly TweenRunner<FloatTween> m_FloatTweenRunner;
protected UIAccordionElement() protected AccordionElement()
{ {
if (this.m_FloatTweenRunner == null) if (this.m_FloatTweenRunner == null)
this.m_FloatTweenRunner = new TweenRunner<FloatTween>(); this.m_FloatTweenRunner = new TweenRunner<FloatTween>();
@ -34,7 +33,7 @@ namespace UnityEngine.UI
base.Awake(); base.Awake();
base.transition = Transition.None; base.transition = Transition.None;
base.toggleTransition = ToggleTransition.None; base.toggleTransition = ToggleTransition.None;
this.m_Accordion = this.gameObject.GetComponentInParent<UIAccordion>(); this.m_Accordion = this.gameObject.GetComponentInParent<Accordion>();
this.m_RectTransform = this.transform as RectTransform; this.m_RectTransform = this.transform as RectTransform;
this.m_LayoutElement = this.gameObject.GetComponent<LayoutElement>(); this.m_LayoutElement = this.gameObject.GetComponent<LayoutElement>();
this.onValueChanged.AddListener(OnValueChanged); this.onValueChanged.AddListener(OnValueChanged);
@ -74,9 +73,9 @@ namespace UnityEngine.UI
if (this.m_LayoutElement == null) if (this.m_LayoutElement == null)
return; return;
UIAccordion.Transition transition = (this.m_Accordion != null) ? this.m_Accordion.transition : UIAccordion.Transition.Instant; Accordion.Transition transition = (this.m_Accordion != null) ? this.m_Accordion.transition : Accordion.Transition.Instant;
if (transition == UIAccordion.Transition.Instant) if (transition == Accordion.Transition.Instant)
{ {
if (state) if (state)
{ {
@ -87,7 +86,7 @@ namespace UnityEngine.UI
this.m_LayoutElement.preferredHeight = this.m_MinHeight; this.m_LayoutElement.preferredHeight = this.m_MinHeight;
} }
} }
else if (transition == UIAccordion.Transition.Tween) else if (transition == Accordion.Transition.Tween)
{ {
if (state) if (state)
{ {

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 53f48a76b4229da449e962fb3aa06279 guid: 3c9d341c4bc7de548937508e6f837144
MonoImporter: MonoImporter:
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []

View File

@ -1,14 +1,12 @@
///Credit ChoMPHi ///Credit ChoMPHi
///Sourced from - http://forum.unity3d.com/threads/accordion-type-layout.271818/ ///Sourced from - http://forum.unity3d.com/threads/accordion-type-layout.271818/
using UnityEngine; using UnityEngine.UI.Extensions;
using UnityEngine.UI;
using System.Collections;
namespace UnityEditor.UI namespace UnityEditor.UI
{ {
[CustomEditor(typeof(UIAccordionElement), true)] [CustomEditor(typeof(AccordionElement), true)]
public class UIAccordionElementEditor : ToggleEditor { public class AccordionElementEditor : ToggleEditor {
public override void OnInspectorGUI() public override void OnInspectorGUI()
{ {

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 65d9021f354adf14ab31e200546fb013 guid: 8882b502b0c65b24ba4623d6a383815b
MonoImporter: MonoImporter:
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []

View File

@ -4,7 +4,7 @@
using System.Collections; using System.Collections;
using UnityEngine.Events; using UnityEngine.Events;
namespace UnityEngine.UI.Tweens namespace UnityEngine.UI.Extensions.Tweens
{ {
public struct FloatTween : ITweenValue public struct FloatTween : ITweenValue
{ {

View File

@ -3,7 +3,7 @@
using System.Collections; using System.Collections;
namespace UnityEngine.UI.Tweens namespace UnityEngine.UI.Extensions.Tweens
{ {
internal interface ITweenValue internal interface ITweenValue
{ {

View File

@ -3,7 +3,7 @@
using System.Collections; using System.Collections;
namespace UnityEngine.UI.Tweens namespace UnityEngine.UI.Extensions.Tweens
{ {
// Tween runner, executes the given tween. // Tween runner, executes the given tween.
// The coroutine will live within the given // The coroutine will live within the given

View File

@ -1,11 +1,10 @@
/// Credit Melang /// Credit Melang
/// Sourced from - http://forum.unity3d.com/members/melang.593409/ /// Sourced from - http://forum.unity3d.com/members/melang.593409/
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace UnityEngine.UI namespace UnityEngine.UI.Extensions
{ {
[AddComponentMenu ("UI/Effects/BestFit Outline", 15)] [AddComponentMenu("UI/Effects/Extensions/BestFit Outline")]
public class BestFitOutline : Shadow public class BestFitOutline : Shadow
{ {
// //
@ -32,8 +31,6 @@ namespace UnityEngine.UI
if (foundtext && foundtext.resizeTextForBestFit) if (foundtext && foundtext.resizeTextForBestFit)
{ {
best_fit_adjustment = (float)foundtext.cachedTextGenerator.fontSizeUsedForBestFit / (foundtext.resizeTextMaxSize-1); //max size seems to be exclusive best_fit_adjustment = (float)foundtext.cachedTextGenerator.fontSizeUsedForBestFit / (foundtext.resizeTextMaxSize-1); //max size seems to be exclusive
//Debug.Log("best_fit_adjustment:"+best_fit_adjustment);
} }
int start = 0; int start = 0;

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 41b373e1e582f0c4286c09ce25cc7021 guid: 7b30dd83a12669d4f973ff5a79ca9842
MonoImporter: MonoImporter:
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []

View File

@ -1,117 +1,116 @@
/// Credit dakka /// Credit dakka
/// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/#post-1752415 /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/#post-1752415
/// Notes - Mod from Yilmaz Kiymaz's editor scripts presentation at Unite 2013 /// Notes - Mod from Yilmaz Kiymaz's editor scripts presentation at Unite 2013
/// Updated ddreaper - removed Linq use, not required.
using UnityEngine;
using UnityEditor; using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class CanvasGroupActivator : EditorWindow { namespace UnityEngine.UI.Extensions
{
[MenuItem ("Window/Tools/Canvas Groups Activator")] public class CanvasGroupActivator : EditorWindow
public static void InitWindow()
{
EditorWindow.GetWindow<CanvasGroupActivator>();
}
List<CanvasGroup> canvasGroups;
void OnEnable()
{
ObtainCanvasGroups();
}
void OnFocus()
{
ObtainCanvasGroups();
}
void ObtainCanvasGroups()
{
canvasGroups = new List<CanvasGroup>();
canvasGroups = GameObject.FindObjectsOfType<CanvasGroup>().ToList();
}
void OnGUI()
{
if (canvasGroups == null)
{
return;
}
GUILayout.Space(10f);
GUILayout.Label("Canvas Groups");
for (int i = 0; i < canvasGroups.Count; i++)
{
if (canvasGroups[i] == null) { continue; }
bool initialActive = false;
if (canvasGroups[i].alpha == 1.0f)
initialActive = true;
bool active = EditorGUILayout.Toggle(canvasGroups[i].name, initialActive);
if (active != initialActive)
{
//If deactivated and initially active
if(!active && initialActive)
{
//Deactivate this
canvasGroups[i].alpha = 0f;
canvasGroups[i].interactable = false;
canvasGroups[i].blocksRaycasts = false;
}
//If activated and initially deactive
else if(active && !initialActive)
{
//Deactivate all others and activate this
HideAllGroups();
canvasGroups[i].alpha = 1.0f;
canvasGroups[i].interactable = true;
canvasGroups[i].blocksRaycasts = true;
}
}
}
GUILayout.Space(5f);
if(GUILayout.Button("Show All"))
{
ShowAllGroups();
}
if(GUILayout.Button ("Hide All"))
{
HideAllGroups();
}
}
void ShowAllGroups()
{ {
canvasGroups.ForEach(x => [MenuItem("Window/UI/Extensions/Canvas Groups Activator")]
public static void InitWindow()
{ {
if (x != null) EditorWindow.GetWindow<CanvasGroupActivator>();
{ }
x.alpha = 1.0f;
x.interactable = true;
x.blocksRaycasts = true;
}
});
}
void HideAllGroups() CanvasGroup[] canvasGroups;
{
canvasGroups.ForEach(x => void OnEnable()
{ {
if (x != null) ObtainCanvasGroups();
}
void OnFocus()
{
ObtainCanvasGroups();
}
void ObtainCanvasGroups()
{
canvasGroups = GameObject.FindObjectsOfType<CanvasGroup>();
}
void OnGUI()
{
if (canvasGroups == null)
{ {
x.alpha = 0f; return;
x.interactable = false;
x.blocksRaycasts = false;
} }
});
GUILayout.Space(10f);
GUILayout.Label("Canvas Groups");
for (int i = 0; i < canvasGroups.Length; i++)
{
if (canvasGroups[i] == null) { continue; }
bool initialActive = false;
if (canvasGroups[i].alpha == 1.0f)
initialActive = true;
bool active = EditorGUILayout.Toggle(canvasGroups[i].name, initialActive);
if (active != initialActive)
{
//If deactivated and initially active
if (!active && initialActive)
{
//Deactivate this
canvasGroups[i].alpha = 0f;
canvasGroups[i].interactable = false;
canvasGroups[i].blocksRaycasts = false;
}
//If activated and initially deactive
else if (active && !initialActive)
{
//Deactivate all others and activate this
HideAllGroups();
canvasGroups[i].alpha = 1.0f;
canvasGroups[i].interactable = true;
canvasGroups[i].blocksRaycasts = true;
}
}
}
GUILayout.Space(5f);
if (GUILayout.Button("Show All"))
{
ShowAllGroups();
}
if (GUILayout.Button("Hide All"))
{
HideAllGroups();
}
}
void ShowAllGroups()
{
foreach (var group in canvasGroups)
{
if (group != null)
{
group.alpha = 1.0f;
group.interactable = true;
group.blocksRaycasts = true;
}
}
}
void HideAllGroups()
{
foreach (var group in canvasGroups)
{
if (group != null)
{
group.alpha = 0;
group.interactable = false;
group.blocksRaycasts = false;
}
}
}
} }
} }

View File

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

5
Scripts/ComboBox.meta Normal file
View File

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

File diff suppressed because it is too large Load Diff

View File

@ -2,95 +2,95 @@
///Sourced from - http://forum.unity3d.com/threads/receive-onclick-event-and-pass-it-on-to-lower-ui-elements.293642/ ///Sourced from - http://forum.unity3d.com/threads/receive-onclick-event-and-pass-it-on-to-lower-ui-elements.293642/
using System; using System;
using UnityEngine;
using UnityEngine.UI;
public class ComboBoxItem namespace UnityEngine.UI.Extensions
{ {
public class ComboBoxItem
[SerializeField]
private string _caption;
/// <summary>
/// Caption of the Item
/// </summary>
public string Caption
{ {
get [SerializeField]
private string _caption;
/// <summary>
/// Caption of the Item
/// </summary>
public string Caption
{ {
return _caption; get
{
return _caption;
}
set
{
_caption = value;
if (OnUpdate != null)
OnUpdate();
}
} }
set
[SerializeField]
private Sprite _image;
/// <summary>
/// Image component of the Item
/// </summary>
public Sprite Image
{ {
_caption = value; get
if (OnUpdate != null) {
OnUpdate(); return _image;
}
set
{
_image = value;
if (OnUpdate != null)
OnUpdate();
}
} }
[SerializeField]
private bool _isDisabled;
/// <summary>
/// Is the Item currently enabled?
/// </summary>
public bool IsDisabled
{
get
{
return _isDisabled;
}
set
{
_isDisabled = value;
if (OnUpdate != null)
OnUpdate();
}
}
public Action OnSelect; //action to be called when this item is selected
internal Action OnUpdate; //action to be called when something changes.
///<remarks> Value exists so that an item can have a caption and a value, like in traditional windows forms. Ie. an item may be a student's name, and the value could be the student's ID number</remarks>
private string _value;
/// <summary>
/// Constructor for ComboBoxOptions
/// </summary>
/// <param name="caption">Caption for the item </param>
/// <param name="val">Value of the item </param>
/// <param name="image"></param>
/// <param name="disabled">Should the item start disabled</param>
/// <param name="onSelect">Action to be called when this item is selected</param>
public ComboBoxItem(string caption = "", string val = "", Sprite image = null, bool disabled = false, Action onSelect = null)
{
_caption = caption;
_image = image;
_value = val;
_isDisabled = disabled;
OnSelect = onSelect;
}
} }
[SerializeField]
private Sprite _image;
/// <summary>
/// Image component of the Item
/// </summary>
public Sprite Image
{
get
{
return _image;
}
set
{
_image = value;
if (OnUpdate != null)
OnUpdate();
}
}
[SerializeField]
private bool _isDisabled;
/// <summary>
/// Is the Item currently enabled?
/// </summary>
public bool IsDisabled
{
get
{
return _isDisabled;
}
set
{
_isDisabled = value;
if (OnUpdate != null)
OnUpdate();
}
}
public Action OnSelect; //action to be called when this item is selected
internal Action OnUpdate; //action to be called when something changes.
///<remarks> Value exists so that an item can have a caption and a value, like in traditional windows forms. Ie. an item may be a student's name, and the value could be the student's ID number</remarks>
private string _value;
/// <summary>
/// Constructor for ComboBoxOptions
/// </summary>
/// <param name="caption">Caption for the item </param>
/// <param name="val">Value of the item </param>
/// <param name="image"></param>
/// <param name="disabled">Should the item start disabled</param>
/// <param name="onSelect">Action to be called when this item is selected</param>
public ComboBoxItem(string caption="",string val="", Sprite image=null, bool disabled=false, Action onSelect=null)
{
_caption = caption;
_image = image;
_value = val;
_isDisabled = disabled;
OnSelect = onSelect;
}
} }

View File

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

View File

@ -1,19 +0,0 @@
///Credit perchik
///Sourced from - http://forum.unity3d.com/threads/receive-onclick-event-and-pass-it-on-to-lower-ui-elements.293642/
using UnityEngine;
using System.Collections;
public class UIManager : MonoBehaviour
{
private static GameObject canvas;
public static GameObject GetCanvas()
{
canvas = FindObjectOfType<Canvas>().gameObject;
return canvas;
}
}

View File

@ -1,62 +1,63 @@
/// Credit Breyer /// Credit Breyer
/// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/#post-1777407 /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/#post-1777407
using UnityEngine; namespace UnityEngine.UI.Extensions
using System.Collections;
using UnityEngine.UI;
using System;
[RequireComponent(typeof(Text),typeof(RectTransform))]
public class CurvedText : BaseVertexEffect
{ {
public AnimationCurve curveForText = AnimationCurve.Linear (0, 0, 1, 10); [RequireComponent(typeof(Text), typeof(RectTransform))]
public float curveMultiplier = 1; [AddComponentMenu("UI/Effects/Extensions/Curved Text")]
private RectTransform rectTrans; public class CurvedText : BaseVertexEffect
{
public AnimationCurve curveForText = AnimationCurve.Linear(0, 0, 1, 10);
public float curveMultiplier = 1;
private RectTransform rectTrans;
#if UNITY_EDITOR #if UNITY_EDITOR
protected override void OnValidate () protected override void OnValidate()
{ {
base.OnValidate (); base.OnValidate();
if (curveForText [0].time != 0) { if (curveForText[0].time != 0)
var tmpRect = curveForText [0]; {
tmpRect.time = 0; var tmpRect = curveForText[0];
curveForText.MoveKey (0, tmpRect); tmpRect.time = 0;
} curveForText.MoveKey(0, tmpRect);
if (rectTrans == null) }
rectTrans = GetComponent<RectTransform> (); if (rectTrans == null)
if (curveForText [curveForText.length - 1].time != rectTrans.rect.width) rectTrans = GetComponent<RectTransform>();
OnRectTransformDimensionsChange (); if (curveForText[curveForText.length - 1].time != rectTrans.rect.width)
} OnRectTransformDimensionsChange();
}
#endif #endif
protected override void Awake () protected override void Awake()
{ {
base.Awake (); base.Awake();
rectTrans = GetComponent<RectTransform> (); rectTrans = GetComponent<RectTransform>();
OnRectTransformDimensionsChange (); OnRectTransformDimensionsChange();
} }
protected override void OnEnable () protected override void OnEnable()
{ {
base.OnEnable (); base.OnEnable();
rectTrans = GetComponent<RectTransform> (); rectTrans = GetComponent<RectTransform>();
OnRectTransformDimensionsChange (); OnRectTransformDimensionsChange();
} }
public override void ModifyVertices (System.Collections.Generic.List<UIVertex> verts) public override void ModifyVertices(System.Collections.Generic.List<UIVertex> verts)
{ {
if (!IsActive ()) if (!IsActive())
return; return;
for (int index = 0; index < verts.Count; index++) { for (int index = 0; index < verts.Count; index++)
var uiVertex = verts [index]; {
//Debug.Log (); var uiVertex = verts[index];
uiVertex.position.y += curveForText.Evaluate (rectTrans.rect.width * rectTrans.pivot.x + uiVertex.position.x) * curveMultiplier; //Debug.Log ();
verts [index] = uiVertex; uiVertex.position.y += curveForText.Evaluate(rectTrans.rect.width * rectTrans.pivot.x + uiVertex.position.x) * curveMultiplier;
} verts[index] = uiVertex;
} }
protected override void OnRectTransformDimensionsChange () }
{ protected override void OnRectTransformDimensionsChange()
var tmpRect = curveForText [curveForText.length - 1]; {
tmpRect.time = rectTrans.rect.width; var tmpRect = curveForText[curveForText.length - 1];
curveForText.MoveKey (curveForText.length - 1, tmpRect); tmpRect.time = rectTrans.rect.width;
} curveForText.MoveKey(curveForText.length - 1, tmpRect);
}
}
} }

View File

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

5
Scripts/Editor.meta Normal file
View File

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

View File

@ -0,0 +1,319 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.UI.Extensions;
namespace UnityEditor.UI
{
/// <summary>
/// This script adds the Extensions UI menu options to the Unity Editor.
/// </summary>
static internal class ExtensionMenuOptions
{
#region Unity Builder section - Do not change unless UI Source (Editor\MenuOptions) changes
#region Unity Builder properties - Do not change unless UI Source (Editor\MenuOptions) changes
private const string kUILayerName = "UI";
private const float kWidth = 160f;
private const float kThickHeight = 30f;
private const float kThinHeight = 20f;
private const string kStandardSpritePath = "UI/Skin/UISprite.psd";
private const string kBackgroundSpriteResourcePath = "UI/Skin/Background.psd";
private const string kInputFieldBackgroundPath = "UI/Skin/InputFieldBackground.psd";
private const string kKnobPath = "UI/Skin/Knob.psd";
private const string kCheckmarkPath = "UI/Skin/Checkmark.psd";
private static Vector2 s_ThickGUIElementSize = new Vector2(kWidth, kThickHeight);
private static Vector2 s_ThinGUIElementSize = new Vector2(kWidth, kThinHeight);
private static Vector2 s_ImageGUIElementSize = new Vector2(100f, 100f);
private static Color s_DefaultSelectableColor = new Color(1f, 1f, 1f, 1f);
#endregion
#region Unity Builder methods - Do not change unless UI Source (Editor\MenuOptions) changes
private static void SetPositionVisibleinSceneView(RectTransform canvasRTransform, RectTransform itemTransform)
{
// Find the best scene view
SceneView sceneView = SceneView.lastActiveSceneView;
if (sceneView == null && SceneView.sceneViews.Count > 0)
sceneView = SceneView.sceneViews[0] as SceneView;
// Couldn't find a SceneView. Don't set position.
if (sceneView == null || sceneView.camera == null)
return;
// Create world space Plane from canvas position.
Vector2 localPlanePosition;
Camera camera = sceneView.camera;
Vector3 position = Vector3.zero;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRTransform, new Vector2(camera.pixelWidth / 2, camera.pixelHeight / 2), camera, out localPlanePosition))
{
// Adjust for canvas pivot
localPlanePosition.x = localPlanePosition.x + canvasRTransform.sizeDelta.x * canvasRTransform.pivot.x;
localPlanePosition.y = localPlanePosition.y + canvasRTransform.sizeDelta.y * canvasRTransform.pivot.y;
localPlanePosition.x = Mathf.Clamp(localPlanePosition.x, 0, canvasRTransform.sizeDelta.x);
localPlanePosition.y = Mathf.Clamp(localPlanePosition.y, 0, canvasRTransform.sizeDelta.y);
// Adjust for anchoring
position.x = localPlanePosition.x - canvasRTransform.sizeDelta.x * itemTransform.anchorMin.x;
position.y = localPlanePosition.y - canvasRTransform.sizeDelta.y * itemTransform.anchorMin.y;
Vector3 minLocalPosition;
minLocalPosition.x = canvasRTransform.sizeDelta.x * (0 - canvasRTransform.pivot.x) + itemTransform.sizeDelta.x * itemTransform.pivot.x;
minLocalPosition.y = canvasRTransform.sizeDelta.y * (0 - canvasRTransform.pivot.y) + itemTransform.sizeDelta.y * itemTransform.pivot.y;
Vector3 maxLocalPosition;
maxLocalPosition.x = canvasRTransform.sizeDelta.x * (1 - canvasRTransform.pivot.x) - itemTransform.sizeDelta.x * itemTransform.pivot.x;
maxLocalPosition.y = canvasRTransform.sizeDelta.y * (1 - canvasRTransform.pivot.y) - itemTransform.sizeDelta.y * itemTransform.pivot.y;
position.x = Mathf.Clamp(position.x, minLocalPosition.x, maxLocalPosition.x);
position.y = Mathf.Clamp(position.y, minLocalPosition.y, maxLocalPosition.y);
}
itemTransform.anchoredPosition = position;
itemTransform.localRotation = Quaternion.identity;
itemTransform.localScale = Vector3.one;
}
private static GameObject CreateUIElementRoot(string name, MenuCommand menuCommand, Vector2 size)
{
GameObject parent = menuCommand.context as GameObject;
if (parent == null || parent.GetComponentInParent<Canvas>() == null)
{
parent = GetOrCreateCanvasGameObject();
}
GameObject child = new GameObject(name);
Undo.RegisterCreatedObjectUndo(child, "Create " + name);
Undo.SetTransformParent(child.transform, parent.transform, "Parent " + child.name);
GameObjectUtility.SetParentAndAlign(child, parent);
RectTransform rectTransform = child.AddComponent<RectTransform>();
rectTransform.sizeDelta = size;
if (parent != menuCommand.context) // not a context click, so center in sceneview
{
SetPositionVisibleinSceneView(parent.GetComponent<RectTransform>(), rectTransform);
}
Selection.activeGameObject = child;
return child;
}
static GameObject CreateUIObject(string name, GameObject parent)
{
GameObject go = new GameObject(name);
go.AddComponent<RectTransform>();
GameObjectUtility.SetParentAndAlign(go, parent);
return go;
}
[MenuItem("GameObject/UI/Canvas", false, 2009)]
static public void AddCanvas(MenuCommand menuCommand)
{
var go = CreateNewUI();
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject);
if (go.transform.parent as RectTransform)
{
RectTransform rect = go.transform as RectTransform;
rect.anchorMin = Vector2.zero;
rect.anchorMax = Vector2.one;
rect.anchoredPosition = Vector2.zero;
rect.sizeDelta = Vector2.zero;
}
Selection.activeGameObject = go;
}
static public GameObject CreateNewUI()
{
// Root for the UI
var root = new GameObject("Canvas");
root.layer = LayerMask.NameToLayer(kUILayerName);
Canvas canvas = root.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
root.AddComponent<CanvasScaler>();
root.AddComponent<GraphicRaycaster>();
Undo.RegisterCreatedObjectUndo(root, "Create " + root.name);
// if there is no event system add one...
CreateEventSystem(false);
return root;
}
[MenuItem("GameObject/UI/EventSystem", false, 2010)]
public static void CreateEventSystem(MenuCommand menuCommand)
{
GameObject parent = menuCommand.context as GameObject;
CreateEventSystem(true, parent);
}
private static void CreateEventSystem(bool select)
{
CreateEventSystem(select, null);
}
private static void CreateEventSystem(bool select, GameObject parent)
{
var esys = Object.FindObjectOfType<EventSystem>();
if (esys == null)
{
var eventSystem = new GameObject("EventSystem");
GameObjectUtility.SetParentAndAlign(eventSystem, parent);
esys = eventSystem.AddComponent<EventSystem>();
eventSystem.AddComponent<StandaloneInputModule>();
eventSystem.AddComponent<TouchInputModule>();
Undo.RegisterCreatedObjectUndo(eventSystem, "Create " + eventSystem.name);
}
if (select && esys != null)
{
Selection.activeGameObject = esys.gameObject;
}
}
// Helper function that returns a Canvas GameObject; preferably a parent of the selection, or other existing Canvas.
static public GameObject GetOrCreateCanvasGameObject()
{
GameObject selectedGo = Selection.activeGameObject;
// Try to find a gameobject that is the selected GO or one if its parents.
Canvas canvas = (selectedGo != null) ? selectedGo.GetComponentInParent<Canvas>() : null;
if (canvas != null && canvas.gameObject.activeInHierarchy)
return canvas.gameObject;
// No canvas in selection or its parents? Then use just any canvas..
canvas = Object.FindObjectOfType(typeof(Canvas)) as Canvas;
if (canvas != null && canvas.gameObject.activeInHierarchy)
return canvas.gameObject;
// No canvas in the scene at all? Then create a new one.
return ExtensionMenuOptions.CreateNewUI();
}
private static void SetDefaultColorTransitionValues(Selectable slider)
{
ColorBlock colors = slider.colors;
colors.highlightedColor = new Color(0.882f, 0.882f, 0.882f);
colors.pressedColor = new Color(0.698f, 0.698f, 0.698f);
colors.disabledColor = new Color(0.521f, 0.521f, 0.521f);
}
#endregion
#endregion
#region UI Extensions "Create" Menu items
[MenuItem("GameObject/UI/Extensions/Horizontal Scroll Snap", false, 2000)]
static public void AddHorizontalScrollSnap(MenuCommand menuCommand)
{
GameObject horizontalScrollSnapRoot = CreateUIElementRoot("Horizontal Scroll Snap", menuCommand, s_ThickGUIElementSize);
// Set RectTransform to stretch
RectTransform rectTransform = horizontalScrollSnapRoot.GetComponent<RectTransform>();
rectTransform.anchorMin = Vector2.zero;
rectTransform.anchorMax = Vector2.one;
rectTransform.anchoredPosition = Vector2.zero;
rectTransform.sizeDelta = Vector2.zero;
Image image = horizontalScrollSnapRoot.AddComponent<Image>();
image.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpriteResourcePath);
image.type = Image.Type.Sliced;
image.color = new Color(1f, 1f, 1f, 0.392f);
ScrollRect sr = horizontalScrollSnapRoot.AddComponent<ScrollRect>();
HorizontalScrollSnap HSS = horizontalScrollSnapRoot.AddComponent<HorizontalScrollSnap>();
Selection.activeGameObject = horizontalScrollSnapRoot;
}
[MenuItem("GameObject/UI/Extensions/UI Button", false, 2001)]
static public void AddUIButton(MenuCommand menuCommand)
{
GameObject uiButtonRoot = CreateUIElementRoot("UI Button", menuCommand, s_ThickGUIElementSize);
GameObject childText = new GameObject("Text");
GameObjectUtility.SetParentAndAlign(childText, uiButtonRoot);
Image image = uiButtonRoot.AddComponent<Image>();
image.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath);
image.type = Image.Type.Sliced;
image.color = s_DefaultSelectableColor;
UIButton bt = uiButtonRoot.AddComponent<UIButton>();
SetDefaultColorTransitionValues(bt);
Text text = childText.AddComponent<Text>();
text.text = "Button";
text.alignment = TextAnchor.MiddleCenter;
text.color = new Color(0.196f, 0.196f, 0.196f);
RectTransform textRectTransform = childText.GetComponent<RectTransform>();
textRectTransform.anchorMin = Vector2.zero;
textRectTransform.anchorMax = Vector2.one;
textRectTransform.sizeDelta = Vector2.zero;
Selection.activeGameObject = uiButtonRoot;
}
[MenuItem("GameObject/UI/Extensions/UI Flippable", false, 2003)]
static public void AddUIFlippableImage(MenuCommand menuCommand)
{
GameObject go = CreateUIElementRoot("UI Flippable", menuCommand, s_ImageGUIElementSize);
go.AddComponent<Image>();
go.AddComponent<UIFlippable>();
Selection.activeGameObject = go;
}
[MenuItem("GameObject/UI/Extensions/UI Window Base", false, 2004)]
static public void AddUIWindowBase(MenuCommand menuCommand)
{
GameObject go = CreateUIElementRoot("UI Window Base", menuCommand, s_ThickGUIElementSize);
go.AddComponent<UIWindowBase>();
Selection.activeGameObject = go;
}
[MenuItem("GameObject/UI/Extensions/Accordion/Accordion Group", false, 2002)]
static public void AddAccordionGroup(MenuCommand menuCommand)
{
GameObject go = CreateUIElementRoot("Accordion Group", menuCommand, s_ThickGUIElementSize);
go.AddComponent<VerticalLayoutGroup>();
go.AddComponent<ContentSizeFitter>();
go.AddComponent<ToggleGroup>();
go.AddComponent<Accordion>();
Selection.activeGameObject = go;
}
[MenuItem("GameObject/UI/Extensions/Accordion/Accordion Element", false, 2002)]
static public void AddAccordionElement(MenuCommand menuCommand)
{
GameObject go = CreateUIElementRoot("Accordion Element", menuCommand, s_ThickGUIElementSize);
go.AddComponent<LayoutElement>();
go.AddComponent<AccordionElement>();
Selection.activeGameObject = go;
}
[MenuItem("GameObject/UI/Extensions/ComboBox", false, 2002)]
static public void AddComboBox(MenuCommand menuCommand)
{
GameObject go = CreateUIElementRoot("ComboBox", menuCommand, s_ThickGUIElementSize);
go.AddComponent<ComboBox>();
Selection.activeGameObject = go;
}
[MenuItem("GameObject/UI/Extensions/Selection Box", false, 2009)]
static public void AddSelectionBox(MenuCommand menuCommand)
{
var go = CreateNewUI();
go.name = "Selection Box";
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject);
if (go.transform.parent as RectTransform)
{
RectTransform rect = go.transform as RectTransform;
rect.anchorMin = Vector2.zero;
rect.anchorMax = Vector2.one;
rect.anchoredPosition = Vector2.zero;
rect.sizeDelta = Vector2.zero;
}
go.AddComponent<SelectionBox>();
Selection.activeGameObject = go;
}
#endregion
}
}

View File

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

View File

@ -1,95 +1,104 @@
/// Credit Breyer /// Credit Breyer
/// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/#post-1780095 /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/#post-1780095
using UnityEngine;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine.UI;
[AddComponentMenu("UI/Effects/Gradient")] namespace UnityEngine.UI.Extensions
public class Gradient : BaseVertexEffect
{ {
public GradientMode gradientMode = GradientMode.Global; [AddComponentMenu("UI/Effects/Extensions/Gradient")]
public GradientDir gradientDir = GradientDir.Vertical; public class Gradient : BaseVertexEffect
public bool overwriteAllColor = false; {
public Color vertex1 = Color.white; public GradientMode gradientMode = GradientMode.Global;
public Color vertex2 = Color.black; public GradientDir gradientDir = GradientDir.Vertical;
private Graphic targetGraphic; public bool overwriteAllColor = false;
public Color vertex1 = Color.white;
public Color vertex2 = Color.black;
private Graphic targetGraphic;
protected override void Start () protected override void Start()
{ {
targetGraphic = GetComponent<Graphic> (); targetGraphic = GetComponent<Graphic>();
} }
public override void ModifyVertices (List<UIVertex> vertexList) public override void ModifyVertices(List<UIVertex> vertexList)
{ {
if (!IsActive () || vertexList.Count == 0) { if (!IsActive() || vertexList.Count == 0)
return; {
} return;
int count = vertexList.Count; }
UIVertex uiVertex = vertexList [0]; int count = vertexList.Count;
if (gradientMode == GradientMode.Global) { UIVertex uiVertex = vertexList[0];
if (gradientDir == GradientDir.DiagonalLeftToRight || gradientDir == GradientDir.DiagonalRightToLeft) { if (gradientMode == GradientMode.Global)
{
if (gradientDir == GradientDir.DiagonalLeftToRight || gradientDir == GradientDir.DiagonalRightToLeft)
{
#if UNITY_EDITOR #if UNITY_EDITOR
Debug.LogWarning("Diagonal dir is not supported in Global mode"); Debug.LogWarning("Diagonal dir is not supported in Global mode");
#endif #endif
gradientDir = GradientDir.Vertical; gradientDir = GradientDir.Vertical;
} }
float bottomY = gradientDir == GradientDir.Vertical ? vertexList [vertexList.Count - 1].position.y : vertexList [vertexList.Count - 1].position.x; float bottomY = gradientDir == GradientDir.Vertical ? vertexList[vertexList.Count - 1].position.y : vertexList[vertexList.Count - 1].position.x;
float topY = gradientDir == GradientDir.Vertical ? vertexList [0].position.y : vertexList [0].position.x; float topY = gradientDir == GradientDir.Vertical ? vertexList[0].position.y : vertexList[0].position.x;
float uiElementHeight = topY - bottomY; float uiElementHeight = topY - bottomY;
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++)
uiVertex = vertexList [i]; {
if (!overwriteAllColor && uiVertex.color != targetGraphic.color) uiVertex = vertexList[i];
continue; if (!overwriteAllColor && uiVertex.color != targetGraphic.color)
uiVertex.color *= Color.Lerp (vertex2, vertex1, ((gradientDir == GradientDir.Vertical ? uiVertex.position.y : uiVertex.position.x) - bottomY) / uiElementHeight); continue;
vertexList [i] = uiVertex; uiVertex.color *= Color.Lerp(vertex2, vertex1, ((gradientDir == GradientDir.Vertical ? uiVertex.position.y : uiVertex.position.x) - bottomY) / uiElementHeight);
} vertexList[i] = uiVertex;
} else { }
for (int i = 0; i < count; i++) { }
uiVertex = vertexList [i]; else
if (!overwriteAllColor && !CompareCarefully (uiVertex.color, targetGraphic.color)) {
continue; for (int i = 0; i < count; i++)
switch (gradientDir) { {
case GradientDir.Vertical: uiVertex = vertexList[i];
uiVertex.color *= (i % 4 == 0 || (i - 1) % 4 == 0) ? vertex1 : vertex2; if (!overwriteAllColor && !CompareCarefully(uiVertex.color, targetGraphic.color))
break; continue;
case GradientDir.Horizontal: switch (gradientDir)
uiVertex.color *= (i % 4 == 0 || (i - 3) % 4 == 0) ? vertex1 : vertex2; {
break; case GradientDir.Vertical:
case GradientDir.DiagonalLeftToRight: uiVertex.color *= (i % 4 == 0 || (i - 1) % 4 == 0) ? vertex1 : vertex2;
uiVertex.color *= (i % 4 == 0) ? vertex1 : ((i - 2) % 4 == 0 ? vertex2 : Color.Lerp (vertex2, vertex1, 0.5f)); break;
break; case GradientDir.Horizontal:
case GradientDir.DiagonalRightToLeft: uiVertex.color *= (i % 4 == 0 || (i - 3) % 4 == 0) ? vertex1 : vertex2;
uiVertex.color *= ((i - 1) % 4 == 0) ? vertex1 : ((i - 3) % 4 == 0 ? vertex2 : Color.Lerp (vertex2, vertex1, 0.5f)); break;
break; case GradientDir.DiagonalLeftToRight:
uiVertex.color *= (i % 4 == 0) ? vertex1 : ((i - 2) % 4 == 0 ? vertex2 : Color.Lerp(vertex2, vertex1, 0.5f));
break;
case GradientDir.DiagonalRightToLeft:
uiVertex.color *= ((i - 1) % 4 == 0) ? vertex1 : ((i - 3) % 4 == 0 ? vertex2 : Color.Lerp(vertex2, vertex1, 0.5f));
break;
} }
vertexList [i] = uiVertex; vertexList[i] = uiVertex;
} }
} }
} }
private bool CompareCarefully (Color col1, Color col2) private bool CompareCarefully(Color col1, Color col2)
{ {
if (Mathf.Abs (col1.r - col2.r) < 0.003f && Mathf.Abs (col1.g - col2.g) < 0.003f && Mathf.Abs (col1.b - col2.b) < 0.003f && Mathf.Abs (col1.a - col2.a) < 0.003f) if (Mathf.Abs(col1.r - col2.r) < 0.003f && Mathf.Abs(col1.g - col2.g) < 0.003f && Mathf.Abs(col1.b - col2.b) < 0.003f && Mathf.Abs(col1.a - col2.a) < 0.003f)
return true; return true;
return false; return false;
} }
}
public enum GradientMode
{
Global,
Local
}
public enum GradientDir
{
Vertical,
Horizontal,
DiagonalLeftToRight,
DiagonalRightToLeft
//Free
}
//enum color mode Additive, Multiply, Overwrite
} }
public enum GradientMode
{
Global,
Local
}
public enum GradientDir
{
Vertical,
Horizontal,
DiagonalLeftToRight,
DiagonalRightToLeft
//Free
}
//enum color mode Additive, Multiply, Overwrite

8
Scripts/Gradient.cs.meta Normal file
View File

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

5
Scripts/HSVPicker.meta Normal file
View File

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

View File

@ -1,26 +1,20 @@
///Credit judah4 ///Credit judah4
///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/ ///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using UnityEngine; namespace UnityEngine.UI.Extensions
using System.Collections;
public class ColorPickerTester : MonoBehaviour
{ {
public class ColorPickerTester : MonoBehaviour
public Renderer renderer;
public HSVPicker picker;
// Use this for initialization
void Start ()
{ {
picker.onValueChanged.AddListener(color => public Renderer renderer;
public HSVPicker picker;
// Use this for initialization
void Start()
{ {
renderer.material.color = color; picker.onValueChanged.AddListener(color =>
}); {
} renderer.material.color = color;
});
// Update is called once per frame }
void Update () { }
}
} }

View File

@ -1,229 +1,228 @@
///Credit judah4 ///Credit judah4
///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/ ///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using UnityEngine; namespace UnityEngine.UI.Extensions
using System.Collections; {
using UnityEngine.UI; public class HSVPicker : MonoBehaviour
using UnityEngine.Events; {
public HexRGB hexrgb;
public class HSVPicker : MonoBehaviour { public Color currentColor;
public Image colorImage;
public Image pointer;
public Image cursor;
public RawImage hsvSlider;
public RawImage hsvImage;
public HexRGB hexrgb; //public InputField inputR;
//public InputField inputG;
//public InputField inputB;
public Color currentColor; public Slider sliderR;
public Image colorImage; public Slider sliderG;
public Image pointer; public Slider sliderB;
public Image cursor; public Text sliderRText;
public RawImage hsvSlider; public Text sliderGText;
public RawImage hsvImage; public Text sliderBText;
//public InputField inputR; public float pointerPos = 0;
//public InputField inputG;
//public InputField inputB;
public Slider sliderR; public float cursorX = 0;
public Slider sliderG; public float cursorY = 0;
public Slider sliderB;
public Text sliderRText;
public Text sliderGText;
public Text sliderBText;
public float pointerPos = 0;
public float cursorX = 0;
public float cursorY = 0;
public HSVSliderEvent onValueChanged = new HSVSliderEvent(); public HSVSliderEvent onValueChanged = new HSVSliderEvent();
private bool dontAssignUpdate = false; private bool dontAssignUpdate = false;
void Awake() void Awake()
{ {
hsvSlider.texture = HSVUtil.GenerateHSVTexture((int)hsvSlider.rectTransform.rect.width, (int)hsvSlider.rectTransform.rect.height); hsvSlider.texture = HSVUtil.GenerateHSVTexture((int)hsvSlider.rectTransform.rect.width, (int)hsvSlider.rectTransform.rect.height);
sliderR.onValueChanged.AddListener(newValue => sliderR.onValueChanged.AddListener(newValue =>
{ {
currentColor.r = newValue; currentColor.r = newValue;
if (dontAssignUpdate == false) if (dontAssignUpdate == false)
{ {
AssignColor(currentColor); AssignColor(currentColor);
} }
sliderRText.text = "R:" + (int)(currentColor.r * 255f); sliderRText.text = "R:" + (int)(currentColor.r * 255f);
hexrgb.ManipulateViaRGB2Hex(); hexrgb.ManipulateViaRGB2Hex();
}); });
sliderG.onValueChanged.AddListener(newValue => sliderG.onValueChanged.AddListener(newValue =>
{ {
currentColor.g = newValue; currentColor.g = newValue;
if (dontAssignUpdate == false) if (dontAssignUpdate == false)
{ {
AssignColor(currentColor); AssignColor(currentColor);
} }
sliderGText.text = "G:" + (int)(currentColor.g * 255f); sliderGText.text = "G:" + (int)(currentColor.g * 255f);
hexrgb.ManipulateViaRGB2Hex(); hexrgb.ManipulateViaRGB2Hex();
}); });
sliderB.onValueChanged.AddListener(newValue => sliderB.onValueChanged.AddListener(newValue =>
{ {
currentColor.b = newValue; currentColor.b = newValue;
if (dontAssignUpdate == false) if (dontAssignUpdate == false)
{ {
AssignColor(currentColor); AssignColor(currentColor);
} }
sliderBText.text = "B:" + (int)(currentColor.b * 255f); sliderBText.text = "B:" + (int)(currentColor.b * 255f);
hexrgb.ManipulateViaRGB2Hex(); hexrgb.ManipulateViaRGB2Hex();
}); });
hsvImage.texture = HSVUtil.GenerateColorTexture((int)hsvImage.rectTransform.rect.width, (int)hsvImage.rectTransform.rect.height, ((Texture2D)hsvSlider.texture).GetPixelBilinear(0, 0)); hsvImage.texture = HSVUtil.GenerateColorTexture((int)hsvImage.rectTransform.rect.width, (int)hsvImage.rectTransform.rect.height, ((Texture2D)hsvSlider.texture).GetPixelBilinear(0, 0));
MoveCursor(cursorX, cursorY); MoveCursor(cursorX, cursorY);
}
// Update is called once per frame
void Update()
{
//if (Input.GetKeyDown(KeyCode.R))
//{
// var color = new Color(45f / 255, 200f / 255, 255f / 255);
// Debug.Log(color);
// AssignColor(color);
// }
}
public void AssignColor(Color color)
{
var hsv = HSVUtil.ConvertRgbToHsv(color);
// Debug.Log(hsv.ToString());
float hOffset = (float)(hsv.H / 360);
//if (hsv.S > 1)
//{
// hsv.S %= 1f;
//}
//if (hsv.V > 1)
//{
// hsv.V %= 1f;
//}
MovePointer(hOffset, false);
MoveCursor((float)hsv.S, (float)hsv.V, false);
currentColor = color;
colorImage.color = currentColor;
onValueChanged.Invoke(currentColor);
}
public Color MoveCursor(float posX, float posY, bool updateInputs = true)
{
dontAssignUpdate = updateInputs;
if (posX > 1)
{
posX %= 1;
}
if (posY > 1)
{
posY %= 1;
}
posY = Mathf.Clamp(posY, 0, .9999f);
posX = Mathf.Clamp(posX, 0, .9999f);
cursorX = posX;
cursorY = posY;
cursor.rectTransform.anchoredPosition = new Vector2(posX * hsvImage.rectTransform.rect.width, posY * hsvImage.rectTransform.rect.height - hsvImage.rectTransform.rect.height);
currentColor = GetColor(cursorX, cursorY);
colorImage.color = currentColor;
if (updateInputs)
{
UpdateInputs();
onValueChanged.Invoke(currentColor);
}
dontAssignUpdate = false;
return currentColor;
}
public Color GetColor(float posX, float posY)
{
//Debug.Log(posX + " " + posY);
return ((Texture2D)hsvImage.texture).GetPixel((int)(cursorX * hsvImage.texture.width), (int)(cursorY * hsvImage.texture.height));
}
public Color MovePointer(float newPos, bool updateInputs = true)
{
dontAssignUpdate = updateInputs;
if (newPos > 1)
{
newPos %= 1f;//hsv
}
pointerPos = newPos;
var mainColor = ((Texture2D)hsvSlider.texture).GetPixelBilinear(0, pointerPos);
if (hsvImage.texture != null)
{
if ((int)hsvImage.rectTransform.rect.width != hsvImage.texture.width || (int)hsvImage.rectTransform.rect.height != hsvImage.texture.height)
{
Destroy(hsvImage.texture);
hsvImage.texture = null;
hsvImage.texture = HSVUtil.GenerateColorTexture((int)hsvImage.rectTransform.rect.width, (int)hsvImage.rectTransform.rect.height, mainColor);
}
else
{
HSVUtil.GenerateColorTexture(mainColor, (Texture2D)hsvImage.texture);
}
}
else
{
hsvImage.texture = HSVUtil.GenerateColorTexture((int)hsvImage.rectTransform.rect.width, (int)hsvImage.rectTransform.rect.height, mainColor);
}
pointer.rectTransform.anchoredPosition = new Vector2(0, -pointerPos * hsvSlider.rectTransform.rect.height);
currentColor = GetColor(cursorX, cursorY);
colorImage.color = currentColor;
if (updateInputs)
{
UpdateInputs();
onValueChanged.Invoke(currentColor);
}
dontAssignUpdate = false;
return currentColor;
}
public void UpdateInputs()
{
sliderR.value = currentColor.r;
sliderG.value = currentColor.g;
sliderB.value = currentColor.b;
sliderRText.text = "R:" + (currentColor.r * 255f);
sliderGText.text = "G:" + (currentColor.g * 255f);
sliderBText.text = "B:" + (currentColor.b * 255f);
}
void OnDestroy()
{
if (hsvSlider.texture != null)
{
Destroy(hsvSlider.texture);
}
if (hsvImage.texture != null)
{
Destroy(hsvImage.texture);
}
}
} }
// Update is called once per frame
void Update () {
//if (Input.GetKeyDown(KeyCode.R))
//{
// var color = new Color(45f / 255, 200f / 255, 255f / 255);
// Debug.Log(color);
// AssignColor(color);
// }
}
public void AssignColor(Color color)
{
var hsv = HSVUtil.ConvertRgbToHsv(color);
// Debug.Log(hsv.ToString());
float hOffset = (float)(hsv.H / 360);
//if (hsv.S > 1)
//{
// hsv.S %= 1f;
//}
//if (hsv.V > 1)
//{
// hsv.V %= 1f;
//}
MovePointer(hOffset, false);
MoveCursor((float)hsv.S, (float)hsv.V, false);
currentColor = color;
colorImage.color = currentColor;
onValueChanged.Invoke(currentColor);
}
public Color MoveCursor(float posX, float posY, bool updateInputs=true)
{
dontAssignUpdate = updateInputs;
if (posX > 1)
{
posX %= 1;
}
if (posY > 1)
{
posY %= 1;
}
posY=Mathf.Clamp(posY, 0, .9999f);
posX =Mathf.Clamp(posX, 0, .9999f);
cursorX = posX;
cursorY = posY;
cursor.rectTransform.anchoredPosition = new Vector2(posX * hsvImage.rectTransform.rect.width, posY * hsvImage.rectTransform.rect.height - hsvImage.rectTransform.rect.height);
currentColor = GetColor(cursorX, cursorY);
colorImage.color = currentColor;
if (updateInputs)
{
UpdateInputs();
onValueChanged.Invoke(currentColor);
}
dontAssignUpdate = false;
return currentColor;
}
public Color GetColor(float posX, float posY)
{
//Debug.Log(posX + " " + posY);
return ((Texture2D)hsvImage.texture).GetPixel((int)(cursorX * hsvImage.texture.width ), (int)(cursorY * hsvImage.texture.height));
}
public Color MovePointer(float newPos, bool updateInputs = true)
{
dontAssignUpdate = updateInputs;
if (newPos > 1)
{
newPos %= 1f;//hsv
}
pointerPos = newPos;
var mainColor =((Texture2D)hsvSlider.texture).GetPixelBilinear(0, pointerPos);
if (hsvImage.texture != null)
{
if ((int)hsvImage.rectTransform.rect.width != hsvImage.texture.width || (int)hsvImage.rectTransform.rect.height != hsvImage.texture.height)
{
Destroy(hsvImage.texture);
hsvImage.texture = null;
hsvImage.texture = HSVUtil.GenerateColorTexture((int)hsvImage.rectTransform.rect.width, (int)hsvImage.rectTransform.rect.height, mainColor);
}
else
{
HSVUtil.GenerateColorTexture(mainColor, (Texture2D)hsvImage.texture);
}
}
else
{
hsvImage.texture = HSVUtil.GenerateColorTexture((int)hsvImage.rectTransform.rect.width, (int)hsvImage.rectTransform.rect.height, mainColor);
}
pointer.rectTransform.anchoredPosition = new Vector2(0, -pointerPos * hsvSlider.rectTransform.rect.height);
currentColor = GetColor(cursorX, cursorY);
colorImage.color = currentColor;
if (updateInputs)
{
UpdateInputs();
onValueChanged.Invoke(currentColor);
}
dontAssignUpdate = false;
return currentColor;
}
public void UpdateInputs()
{
sliderR.value = currentColor.r;
sliderG.value = currentColor.g;
sliderB.value = currentColor.b;
sliderRText.text = "R:"+ (currentColor.r * 255f);
sliderGText.text = "G:" + (currentColor.g * 255f);
sliderBText.text = "B:" + (currentColor.b * 255f);
}
void OnDestroy()
{
if (hsvSlider.texture != null)
{
Destroy(hsvSlider.texture);
}
if (hsvImage.texture != null)
{
Destroy(hsvImage.texture);
}
}
} }

View File

@ -1,20 +1,11 @@
///Credit judah4 ///Credit judah4
///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/ ///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using UnityEngine;
using System.Collections;
using UnityEngine.Events; using UnityEngine.Events;
namespace UnityEngine.UI.Extensions
public class HSVSliderEvent : UnityEvent<Color>
{ {
public class HSVSliderEvent : UnityEvent<Color>
{
// Use this for initialization }
void Start () {
}
// Update is called once per frame
void Update () {
}
} }

View File

@ -1,13 +1,11 @@
///Credit judah4 ///Credit judah4
///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/ ///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System; using System;
using System.Collections.Generic;
namespace UnityEngine.UI.Extensions
{
#region ColorUtilities #region ColorUtilities
public static class HSVUtil public static class HSVUtil
@ -192,7 +190,7 @@ using System;
var texture = new Texture2D(width, height); var texture = new Texture2D(width, height);
int ySize = Mathf.Max(1,(int)(1f/(list.Count/interval) * height)); int ySize = Mathf.Max(1, (int)(1f / (list.Count / interval) * height));
int colorH = 0; int colorH = 0;
@ -200,7 +198,7 @@ using System;
for (float cnt = 0; cnt < list.Count; cnt += interval) for (float cnt = 0; cnt < list.Count; cnt += interval)
{ {
color = list[(int)cnt]; color = list[(int)cnt];
Color[] colors = new Color[width *ySize]; Color[] colors = new Color[width * ySize];
for (int i = 0; i < width * ySize; i++) for (int i = 0; i < width * ySize; i++)
{ {
colors[i] = color; colors[i] = color;
@ -273,10 +271,8 @@ using System;
public override string ToString() public override string ToString()
{ {
return "{"+H+","+S+","+V+"}"; return "{" + H + "," + S + "," + V + "}";
} }
} }
#endregion HsvColor #endregion HsvColor
}

View File

@ -1,75 +1,79 @@
///Credit judah4 ///Credit judah4
///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/ ///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Text;
using System.Globalization; using System.Globalization;
public class HexRGB : MonoBehaviour { namespace UnityEngine.UI.Extensions
{
public class HexRGB : MonoBehaviour
{
public Text textColor;
public Text textColor; public HSVPicker hsvpicker;
public HSVPicker hsvpicker; public void ManipulateViaRGB2Hex()
{
Color color = hsvpicker.currentColor;
string hex = ColorToHex(color);
textColor.text = hex;
}
public void ManipulateViaRGB2Hex(){ public static string ColorToHex(Color color)
Color color = hsvpicker.currentColor; {
string hex = ColorToHex (color); int r = (int)(color.r * 255);
textColor.text = hex; int g = (int)(color.g * 255);
} int b = (int)(color.b * 255);
return string.Format("#{0:X2}{1:X2}{2:X2}", r, g, b);
}
public static string ColorToHex(Color color){ public void ManipulateViaHex2RGB()
int r = (int)(color.r * 255); {
int g = (int)(color.g * 255); string hex = textColor.text;
int b = (int)(color.b * 255);
return string.Format ("#{0:X2}{1:X2}{2:X2}", r, g, b);
}
public void ManipulateViaHex2RGB(){ Vector3 rgb = Hex2RGB(hex);
string hex = textColor.text; Color color = NormalizeVector4(rgb, 255f, 1f); print(rgb);
Vector3 rgb = Hex2RGB (hex); hsvpicker.AssignColor(color);
Color color = NormalizeVector4 (rgb,255f,1f); print (rgb); }
hsvpicker.AssignColor (color); static Color NormalizeVector4(Vector3 v, float r, float a)
} {
float red = v.x / r;
float green = v.y / r;
float blue = v.z / r;
return new Color(red, green, blue, a);
}
static Color NormalizeVector4(Vector3 v,float r,float a){ Vector3 Hex2RGB(string hexColor)
float red = v.x / r; {
float green = v.y / r; //Remove # if present
float blue = v.z / r; if (hexColor.IndexOf('#') != -1)
return new Color (red,green,blue,a); hexColor = hexColor.Replace("#", "");
}
Vector3 Hex2RGB(string hexColor){ int red = 0;
//Remove # if present int green = 0;
if (hexColor.IndexOf('#') != -1) int blue = 0;
hexColor = hexColor.Replace("#", "");
int red = 0; if (hexColor.Length == 6)
int green = 0; {
int blue = 0; //#RRGGBB
red = int.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier);
if (hexColor.Length == 6) green = int.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier);
{ blue = int.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier);
//#RRGGBB
red = int.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier);
green = int.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier);
blue = int.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier);
} }
else if (hexColor.Length == 3) else if (hexColor.Length == 3)
{ {
//#RGB //#RGB
red = int.Parse(hexColor[0].ToString() + hexColor[0].ToString(), NumberStyles.AllowHexSpecifier); red = int.Parse(hexColor[0].ToString() + hexColor[0].ToString(), NumberStyles.AllowHexSpecifier);
green = int.Parse(hexColor[1].ToString() + hexColor[1].ToString(), NumberStyles.AllowHexSpecifier); green = int.Parse(hexColor[1].ToString() + hexColor[1].ToString(), NumberStyles.AllowHexSpecifier);
blue = int.Parse(hexColor[2].ToString() + hexColor[2].ToString(), NumberStyles.AllowHexSpecifier); blue = int.Parse(hexColor[2].ToString() + hexColor[2].ToString(), NumberStyles.AllowHexSpecifier);
} }
return new Vector3 (red, green, blue); return new Vector3(red, green, blue);
} }
}
} }

View File

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

View File

@ -1,48 +1,38 @@
///Credit judah4 ///Credit judah4
///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/ ///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
public class HsvBoxSelector : MonoBehaviour, IDragHandler, IPointerDownHandler { namespace UnityEngine.UI.Extensions
{
public HSVPicker picker; public class HsvBoxSelector : MonoBehaviour, IDragHandler, IPointerDownHandler
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void PlaceCursor(PointerEventData eventData)
{ {
public HSVPicker picker;
var pos = new Vector2(eventData.position.x - picker.hsvImage.rectTransform.position.x, picker.hsvImage.rectTransform.rect.height * picker.hsvImage.transform.lossyScale.y - (picker.hsvImage.rectTransform.position.y - eventData.position.y)); void PlaceCursor(PointerEventData eventData)
// Debug.Log(pos); {
pos.x /= picker.hsvImage.rectTransform.rect.width * picker.hsvImage.transform.lossyScale.x;
pos.y /= picker.hsvImage.rectTransform.rect.height * picker.hsvImage.transform.lossyScale.y;
pos.x = Mathf.Clamp(pos.x, 0, .9999f); //1 is the same as 0 var pos = new Vector2(eventData.position.x - picker.hsvImage.rectTransform.position.x, picker.hsvImage.rectTransform.rect.height * picker.hsvImage.transform.lossyScale.y - (picker.hsvImage.rectTransform.position.y - eventData.position.y));
pos.y = Mathf.Clamp(pos.y, 0, .9999f); // Debug.Log(pos);
pos.x /= picker.hsvImage.rectTransform.rect.width * picker.hsvImage.transform.lossyScale.x;
pos.y /= picker.hsvImage.rectTransform.rect.height * picker.hsvImage.transform.lossyScale.y;
//Debug.Log(pos); pos.x = Mathf.Clamp(pos.x, 0, .9999f); //1 is the same as 0
picker.MoveCursor(pos.x, pos.y); pos.y = Mathf.Clamp(pos.y, 0, .9999f);
}
//Debug.Log(pos);
picker.MoveCursor(pos.x, pos.y);
}
public void OnDrag(PointerEventData eventData) public void OnDrag(PointerEventData eventData)
{ {
PlaceCursor(eventData); PlaceCursor(eventData);
}
} public void OnPointerDown(PointerEventData eventData)
{
public void OnPointerDown(PointerEventData eventData) PlaceCursor(eventData);
{ }
PlaceCursor(eventData);
} }
} }

View File

@ -1,49 +1,37 @@
///Credit judah4 ///Credit judah4
///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/ ///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
public class HsvSliderPicker : MonoBehaviour, IDragHandler, IPointerDownHandler namespace UnityEngine.UI.Extensions
{ {
public class HsvSliderPicker : MonoBehaviour, IDragHandler, IPointerDownHandler
public HSVPicker picker;
// Use this for initialization
void Start()
{ {
public HSVPicker picker;
} void PlacePointer(PointerEventData eventData)
{
// Update is called once per frame var pos = new Vector2(eventData.position.x - picker.hsvSlider.rectTransform.position.x, picker.hsvSlider.rectTransform.position.y - eventData.position.y);
void Update()
{
} pos.y /= picker.hsvSlider.rectTransform.rect.height * picker.hsvSlider.canvas.transform.lossyScale.y;
void PlacePointer(PointerEventData eventData) //Debug.Log(eventData.position.ToString() + " " + picker.hsvSlider.rectTransform.position + " " + picker.hsvSlider.rectTransform.rect.height);
{ pos.y = Mathf.Clamp(pos.y, 0, 1f);
var pos = new Vector2(eventData.position.x - picker.hsvSlider.rectTransform.position.x, picker.hsvSlider.rectTransform.position.y - eventData.position.y); picker.MovePointer(pos.y);
}
pos.y /= picker.hsvSlider.rectTransform.rect.height * picker.hsvSlider.canvas.transform.lossyScale.y;
//Debug.Log(eventData.position.ToString() + " " + picker.hsvSlider.rectTransform.position + " " + picker.hsvSlider.rectTransform.rect.height);
pos.y = Mathf.Clamp(pos.y, 0, 1f);
picker.MovePointer(pos.y);
}
public void OnDrag(PointerEventData eventData) public void OnDrag(PointerEventData eventData)
{ {
PlacePointer(eventData); PlacePointer(eventData);
} }
public void OnPointerDown(PointerEventData eventData) public void OnPointerDown(PointerEventData eventData)
{ {
PlacePointer(eventData); PlacePointer(eventData);
}
} }
} }

View File

@ -3,255 +3,262 @@
/// Updated by ddreaper - removed dependency on a custom ScrollRect script. Now implements drag interfaces and standard Scroll Rect. /// Updated by ddreaper - removed dependency on a custom ScrollRect script. Now implements drag interfaces and standard Scroll Rect.
using System; using System;
using UnityEngine;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(ScrollRect))] namespace UnityEngine.UI.Extensions
public class HorizontalScrollSnap : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{ {
private Transform _screensContainer; [RequireComponent(typeof(ScrollRect))]
[AddComponentMenu("UI/Extensions/Horizontal Scroll Snap")]
private int _screens = 1; public class HorizontalScrollSnap : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
private int _startingScreen = 1;
private bool _fastSwipeTimer = false;
private int _fastSwipeCounter = 0;
private int _fastSwipeTarget = 30;
private System.Collections.Generic.List<Vector3> _positions;
private ScrollRect _scroll_rect;
private Vector3 _lerp_target;
private bool _lerp;
private int _containerSize;
[Tooltip("The gameobject that contains toggles which suggest pagination. THIS CAN BE MISSING")]
public GameObject Pagination;
[Tooltip("Button to go to the next page. (optional)")]
public GameObject NextButton;
[Tooltip("Button to go to the previous page. (optional)")]
public GameObject PrevButton;
public Boolean UseFastSwipe = true;
public int FastSwipeThreshold = 100;
private bool _startDrag = true;
private Vector3 _startPosition = new Vector3();
private int _currentScreen;
// Use this for initialization
void Start()
{ {
_scroll_rect = gameObject.GetComponent<ScrollRect>(); private Transform _screensContainer;
_screensContainer = _scroll_rect.content;
DistributePages();
_screens = _screensContainer.childCount; private int _screens = 1;
private int _startingScreen = 1;
_lerp = false; private bool _fastSwipeTimer = false;
private int _fastSwipeCounter = 0;
private int _fastSwipeTarget = 30;
_positions = new System.Collections.Generic.List<Vector3>();
if (_screens > 0) private System.Collections.Generic.List<Vector3> _positions;
private ScrollRect _scroll_rect;
private Vector3 _lerp_target;
private bool _lerp;
private int _containerSize;
[Tooltip("The gameobject that contains toggles which suggest pagination. (optional)")]
public GameObject Pagination;
[Tooltip("Button to go to the next page. (optional)")]
public GameObject NextButton;
[Tooltip("Button to go to the previous page. (optional)")]
public GameObject PrevButton;
public Boolean UseFastSwipe = true;
public int FastSwipeThreshold = 100;
private bool _startDrag = true;
private Vector3 _startPosition = new Vector3();
private int _currentScreen;
// Use this for initialization
void Start()
{ {
for (int i = 0; i < _screens; ++i) _scroll_rect = gameObject.GetComponent<ScrollRect>();
_screensContainer = _scroll_rect.content;
DistributePages();
_screens = _screensContainer.childCount;
_lerp = false;
_positions = new System.Collections.Generic.List<Vector3>();
if (_screens > 0)
{ {
_scroll_rect.horizontalNormalizedPosition = (float)i / (float)(_screens - 1); for (int i = 0; i < _screens; ++i)
_positions.Add(_screensContainer.localPosition); {
_scroll_rect.horizontalNormalizedPosition = (float)i / (float)(_screens - 1);
_positions.Add(_screensContainer.localPosition);
}
}
_scroll_rect.horizontalNormalizedPosition = (float)(_startingScreen - 1) / (float)(_screens - 1);
_containerSize = (int)_screensContainer.gameObject.GetComponent<RectTransform>().offsetMax.x;
ChangeBulletsInfo(CurrentScreen());
if (NextButton)
NextButton.GetComponent<Button>().onClick.AddListener(() => { NextScreen(); });
if (PrevButton)
PrevButton.GetComponent<Button>().onClick.AddListener(() => { PreviousScreen(); });
}
void Update()
{
if (_lerp)
{
_screensContainer.localPosition = Vector3.Lerp(_screensContainer.localPosition, _lerp_target, 7.5f * Time.deltaTime);
if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 0.005f)
{
_lerp = false;
}
//change the info bullets at the bottom of the screen. Just for visual effect
if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 10f)
{
ChangeBulletsInfo(CurrentScreen());
}
}
if (_fastSwipeTimer)
{
_fastSwipeCounter++;
}
}
private bool fastSwipe = false; //to determine if a fast swipe was performed
//Function for switching screens with buttons
public void NextScreen()
{
if (CurrentScreen() < _screens - 1)
{
_lerp = true;
_lerp_target = _positions[CurrentScreen() + 1];
ChangeBulletsInfo(CurrentScreen() + 1);
} }
} }
_scroll_rect.horizontalNormalizedPosition = (float)(_startingScreen - 1) / (float)(_screens - 1); //Function for switching screens with buttons
public void PreviousScreen()
_containerSize = (int)_screensContainer.gameObject.GetComponent<RectTransform>().offsetMax.x;
ChangeBulletsInfo(CurrentScreen());
if (NextButton)
NextButton.GetComponent<Button>().onClick.AddListener(() => { NextScreen(); });
if (PrevButton)
PrevButton.GetComponent<Button>().onClick.AddListener(() => { PreviousScreen(); });
}
void Update()
{
if (_lerp)
{ {
_screensContainer.localPosition = Vector3.Lerp(_screensContainer.localPosition, _lerp_target, 7.5f * Time.deltaTime); if (CurrentScreen() > 0)
if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 0.005f)
{ {
_lerp = false; _lerp = true;
} _lerp_target = _positions[CurrentScreen() - 1];
//change the info bullets at the bottom of the screen. Just for visual effect ChangeBulletsInfo(CurrentScreen() - 1);
if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 10f)
{
ChangeBulletsInfo(CurrentScreen());
} }
} }
if (_fastSwipeTimer) //Because the CurrentScreen function is not so reliable, these are the functions used for swipes
private void NextScreenCommand()
{ {
_fastSwipeCounter++; if (_currentScreen < _screens - 1)
}
}
private bool fastSwipe = false; //to determine if a fast swipe was performed
//Function for switching screens with buttons
public void NextScreen()
{
if (CurrentScreen() < _screens - 1)
{
_lerp = true;
_lerp_target = _positions[CurrentScreen() + 1];
ChangeBulletsInfo(CurrentScreen() + 1);
}
}
//Function for switching screens with buttons
public void PreviousScreen()
{
if (CurrentScreen() > 0)
{
_lerp = true;
_lerp_target = _positions[CurrentScreen() - 1];
ChangeBulletsInfo(CurrentScreen() - 1);
}
}
//Because the CurrentScreen function is not so reliable, these are the functions used for swipes
private void NextScreenCommand()
{
if (_currentScreen < _screens - 1)
{
_lerp = true;
_lerp_target = _positions[_currentScreen + 1];
ChangeBulletsInfo(_currentScreen + 1);
}
}
//Because the CurrentScreen function is not so reliable, these are the functions used for swipes
private void PrevScreenCommand()
{
if (_currentScreen > 0)
{
_lerp = true;
_lerp_target = _positions[_currentScreen - 1];
ChangeBulletsInfo(_currentScreen - 1);
}
}
//find the closest registered point to the releasing point
private Vector3 FindClosestFrom(Vector3 start, System.Collections.Generic.List<Vector3> positions)
{
Vector3 closest = Vector3.zero;
float distance = Mathf.Infinity;
foreach (Vector3 position in _positions)
{
if (Vector3.Distance(start, position) < distance)
{ {
distance = Vector3.Distance(start, position); _lerp = true;
closest = position; _lerp_target = _positions[_currentScreen + 1];
ChangeBulletsInfo(_currentScreen + 1);
} }
} }
return closest; //Because the CurrentScreen function is not so reliable, these are the functions used for swipes
} private void PrevScreenCommand()
{
if (_currentScreen > 0)
//returns the current screen that the is seeing
public int CurrentScreen()
{
float absPoz = Math.Abs(_screensContainer.gameObject.GetComponent<RectTransform>().offsetMin.x);
absPoz = Mathf.Clamp(absPoz, 1, _containerSize - 1);
float calc = ( absPoz / _containerSize) * _screens;
return (int) calc;
}
//changes the bullets on the bottom of the page - pagination
private void ChangeBulletsInfo(int currentScreen)
{
if (Pagination)
for (int i = 0; i < Pagination.transform.childCount; i++)
{ {
_lerp = true;
_lerp_target = _positions[_currentScreen - 1];
ChangeBulletsInfo(_currentScreen - 1);
}
}
//find the closest registered point to the releasing point
private Vector3 FindClosestFrom(Vector3 start, System.Collections.Generic.List<Vector3> positions)
{
Vector3 closest = Vector3.zero;
float distance = Mathf.Infinity;
foreach (Vector3 position in _positions)
{
if (Vector3.Distance(start, position) < distance)
{
distance = Vector3.Distance(start, position);
closest = position;
}
}
return closest;
}
//returns the current screen that the is seeing
public int CurrentScreen()
{
float absPoz = Math.Abs(_screensContainer.gameObject.GetComponent<RectTransform>().offsetMin.x);
absPoz = Mathf.Clamp(absPoz, 1, _containerSize - 1);
float calc = (absPoz / _containerSize) * _screens;
return (int)calc;
}
//changes the bullets on the bottom of the page - pagination
private void ChangeBulletsInfo(int currentScreen)
{
if (Pagination)
for (int i = 0; i < Pagination.transform.childCount; i++)
{
Pagination.transform.GetChild(i).GetComponent<Toggle>().isOn = (currentScreen == i) Pagination.transform.GetChild(i).GetComponent<Toggle>().isOn = (currentScreen == i)
? true ? true
: false; : false;
} }
}
//used for changing between screen resolutions
private void DistributePages()
{
int _offset = 0;
int _step = Screen.width;
int _dimension = 0;
int currentXPosition = 0;
for (int i = 0; i < _screensContainer.transform.childCount; i++)
{
RectTransform child = _screensContainer.transform.GetChild(i).gameObject.GetComponent<RectTransform>();
currentXPosition = _offset + i * _step;
child.anchoredPosition = new Vector2(currentXPosition, 0f);
child.sizeDelta = new Vector2( gameObject.GetComponent<RectTransform>().sizeDelta.x, gameObject.GetComponent<RectTransform>().sizeDelta.y );
} }
_dimension = currentXPosition + _offset * -1; //used for changing between screen resolutions
private void DistributePages()
_screensContainer.GetComponent<RectTransform>().offsetMax = new Vector2(_dimension, 0f);
}
#region Interfaces
public void OnBeginDrag(PointerEventData eventData)
{
_startPosition = _screensContainer.localPosition;
_fastSwipeCounter = 0;
_fastSwipeTimer = true;
_currentScreen = CurrentScreen();
}
public void OnEndDrag(PointerEventData eventData)
{
_startDrag = true;
if (_scroll_rect.horizontal)
{ {
if (UseFastSwipe) int _offset = 0;
int _step = Screen.width;
int _dimension = 0;
int currentXPosition = 0;
for (int i = 0; i < _screensContainer.transform.childCount; i++)
{ {
fastSwipe = false; RectTransform child = _screensContainer.transform.GetChild(i).gameObject.GetComponent<RectTransform>();
_fastSwipeTimer = false; currentXPosition = _offset + i * _step;
if (_fastSwipeCounter <= _fastSwipeTarget) child.anchoredPosition = new Vector2(currentXPosition, 0f);
child.sizeDelta = new Vector2(gameObject.GetComponent<RectTransform>().sizeDelta.x, gameObject.GetComponent<RectTransform>().sizeDelta.y);
}
_dimension = currentXPosition + _offset * -1;
_screensContainer.GetComponent<RectTransform>().offsetMax = new Vector2(_dimension, 0f);
}
#region Interfaces
public void OnBeginDrag(PointerEventData eventData)
{
_startPosition = _screensContainer.localPosition;
_fastSwipeCounter = 0;
_fastSwipeTimer = true;
_currentScreen = CurrentScreen();
}
public void OnEndDrag(PointerEventData eventData)
{
_startDrag = true;
if (_scroll_rect.horizontal)
{
if (UseFastSwipe)
{ {
if (Math.Abs(_startPosition.x - _screensContainer.localPosition.x) > FastSwipeThreshold) fastSwipe = false;
_fastSwipeTimer = false;
if (_fastSwipeCounter <= _fastSwipeTarget)
{ {
fastSwipe = true; if (Math.Abs(_startPosition.x - _screensContainer.localPosition.x) > FastSwipeThreshold)
{
fastSwipe = true;
}
} }
} if (fastSwipe)
if (fastSwipe)
{
if (_startPosition.x - _screensContainer.localPosition.x > 0)
{ {
NextScreenCommand(); if (_startPosition.x - _screensContainer.localPosition.x > 0)
{
NextScreenCommand();
}
else
{
PrevScreenCommand();
}
} }
else else
{ {
PrevScreenCommand(); _lerp = true;
_lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions);
} }
} }
else else
@ -260,22 +267,17 @@ public class HorizontalScrollSnap : MonoBehaviour, IBeginDragHandler, IEndDragHa
_lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions); _lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions);
} }
} }
else }
public void OnDrag(PointerEventData eventData)
{
_lerp = false;
if (_startDrag)
{ {
_lerp = true; OnBeginDrag(eventData);
_lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions); _startDrag = false;
} }
} }
#endregion
} }
public void OnDrag(PointerEventData eventData)
{
_lerp = false;
if (_startDrag)
{
OnBeginDrag(eventData);
_startDrag = false;
}
}
#endregion
} }

View File

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

View File

@ -41,14 +41,11 @@ break down entirely, but it doesn't really do what you'd want either.
*/ */
using UnityEngine;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
namespace UnityEngine.UI.Extensions
namespace UnityEngine.UI
{ {
[AddComponentMenu("UI/Effects/Letter Spacing", 14)] [AddComponentMenu("UI/Effects/Extensions/Letter Spacing")]
public class LetterSpacing : BaseVertexEffect public class LetterSpacing : BaseVertexEffect
{ {
[SerializeField] [SerializeField]

View File

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

View File

@ -1,12 +1,11 @@
/// Credit Melang /// Credit Melang
/// Sourced from - http://forum.unity3d.com/members/melang.593409/ /// Sourced from - http://forum.unity3d.com/members/melang.593409/
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace UnityEngine.UI namespace UnityEngine.UI.Extensions
{ {
//An outline that looks a bit nicer than the default one. It has less "holes" in the outline by drawing more copies of the effect //An outline that looks a bit nicer than the default one. It has less "holes" in the outline by drawing more copies of the effect
[AddComponentMenu ("UI/Effects/NicerOutline", 15)] [AddComponentMenu("UI/Effects/Extensions/Nicer Outline")]
public class NicerOutline : BaseVertexEffect public class NicerOutline : BaseVertexEffect
{ {
[SerializeField] [SerializeField]

View File

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

View File

@ -25,101 +25,101 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
\***************************************************************************/ \***************************************************************************/
#if UNITY_4_6
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(RectTransform))] namespace UnityEngine.UI.Extensions
[RequireComponent(typeof(Image))]
public class RaycastMask : MonoBehaviour, ICanvasRaycastFilter
{ {
private Image _image; [RequireComponent(typeof(RectTransform))]
private Sprite _sprite; [RequireComponent(typeof(Image))]
[AddComponentMenu("UI/Extensions/Raycast Mask")]
void Start () public class RaycastMask : MonoBehaviour, ICanvasRaycastFilter
{ {
_image = GetComponent<Image>(); private Image _image;
} private Sprite _sprite;
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera) void Start()
{
_sprite = _image.sprite;
var rectTransform = (RectTransform)transform;
Vector2 localPositionPivotRelative;
RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform) transform, sp, eventCamera, out localPositionPivotRelative);
// convert to bottom-left origin coordinates
var localPosition = new Vector2(localPositionPivotRelative.x + rectTransform.pivot.x*rectTransform.rect.width,
localPositionPivotRelative.y + rectTransform.pivot.y*rectTransform.rect.height);
var spriteRect = _sprite.textureRect;
var maskRect = rectTransform.rect;
var x = 0;
var y = 0;
// convert to texture space
switch (_image.type)
{ {
_image = GetComponent<Image>();
}
case Image.Type.Sliced: public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
{
_sprite = _image.sprite;
var rectTransform = (RectTransform)transform;
Vector2 localPositionPivotRelative;
RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)transform, sp, eventCamera, out localPositionPivotRelative);
// convert to bottom-left origin coordinates
var localPosition = new Vector2(localPositionPivotRelative.x + rectTransform.pivot.x * rectTransform.rect.width,
localPositionPivotRelative.y + rectTransform.pivot.y * rectTransform.rect.height);
var spriteRect = _sprite.textureRect;
var maskRect = rectTransform.rect;
var x = 0;
var y = 0;
// convert to texture space
switch (_image.type)
{ {
var border = _sprite.border;
// x slicing
if (localPosition.x < border.x)
{
x = Mathf.FloorToInt(spriteRect.x + localPosition.x);
}
else if (localPosition.x > maskRect.width - border.z)
{
x = Mathf.FloorToInt(spriteRect.x + spriteRect.width - (maskRect.width - localPosition.x));
}
else
{
x = Mathf.FloorToInt(spriteRect.x + border.x +
((localPosition.x - border.x)/
(maskRect.width - border.x - border.z)) *
(spriteRect.width - border.x - border.z));
}
// y slicing
if (localPosition.y < border.y)
{
y = Mathf.FloorToInt(spriteRect.y + localPosition.y);
}
else if (localPosition.y > maskRect.height - border.w)
{
y = Mathf.FloorToInt(spriteRect.y + spriteRect.height - (maskRect.height - localPosition.y));
}
else
{
y = Mathf.FloorToInt(spriteRect.y + border.y +
((localPosition.y - border.y) /
(maskRect.height - border.y - border.w)) *
(spriteRect.height - border.y - border.w));
}
}
break;
case Image.Type.Simple:
default:
{
// conversion to uniform UV space
x = Mathf.FloorToInt(spriteRect.x + spriteRect.width * localPosition.x / maskRect.width);
y = Mathf.FloorToInt(spriteRect.y + spriteRect.height * localPosition.y / maskRect.height);
}
break;
}
// destroy component if texture import settings are wrong case Image.Type.Sliced:
try {
{ var border = _sprite.border;
return _sprite.texture.GetPixel(x,y).a > 0; // x slicing
} if (localPosition.x < border.x)
catch (UnityException) {
{ x = Mathf.FloorToInt(spriteRect.x + localPosition.x);
Debug.LogWarning("Mask texture not readable, set your sprite to Texture Type 'Advanced' and check 'Read/Write Enabled'"); }
Destroy(this); else if (localPosition.x > maskRect.width - border.z)
return false; {
x = Mathf.FloorToInt(spriteRect.x + spriteRect.width - (maskRect.width - localPosition.x));
}
else
{
x = Mathf.FloorToInt(spriteRect.x + border.x +
((localPosition.x - border.x) /
(maskRect.width - border.x - border.z)) *
(spriteRect.width - border.x - border.z));
}
// y slicing
if (localPosition.y < border.y)
{
y = Mathf.FloorToInt(spriteRect.y + localPosition.y);
}
else if (localPosition.y > maskRect.height - border.w)
{
y = Mathf.FloorToInt(spriteRect.y + spriteRect.height - (maskRect.height - localPosition.y));
}
else
{
y = Mathf.FloorToInt(spriteRect.y + border.y +
((localPosition.y - border.y) /
(maskRect.height - border.y - border.w)) *
(spriteRect.height - border.y - border.w));
}
}
break;
case Image.Type.Simple:
default:
{
// conversion to uniform UV space
x = Mathf.FloorToInt(spriteRect.x + spriteRect.width * localPosition.x / maskRect.width);
y = Mathf.FloorToInt(spriteRect.y + spriteRect.height * localPosition.y / maskRect.height);
}
break;
}
// destroy component if texture import settings are wrong
try
{
return _sprite.texture.GetPixel(x, y).a > 0;
}
catch (UnityException)
{
Debug.LogWarning("Mask texture not readable, set your sprite to Texture Type 'Advanced' and check 'Read/Write Enabled'");
Destroy(this);
return false;
}
} }
} }
} }
#endif

View File

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

View File

@ -1,46 +1,36 @@
/// Credit Melang /// Credit Melang
/// Sourced from - http://forum.unity3d.com/members/melang.593409/ /// Sourced from - http://forum.unity3d.com/members/melang.593409/
/// Updated ddreaper - reworked to 4.6.1 standards
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
using System.Collections; namespace UnityEngine.UI
{
[RequireComponent(typeof(InputField))]
[AddComponentMenu("UI/Extensions/Return Key Trigger")]
public class ReturnKeyTriggersButton : MonoBehaviour, ISubmitHandler
{
private EventSystem _system;
public class ReturnKeyTriggersButton : MonoBehaviour { public Button button;
private bool highlight = true;
public float highlightDuration = 0.2f;
EventSystem system; void Start()
InputField field; {
_system = EventSystem.current;
}
public UnityEngine.UI.Button button; void RemoveHighlight()
public bool highlight = true; {
public float highlightDuration = 0.2f; button.OnPointerExit(new PointerEventData(_system));
}
void Start () public void OnSubmit(BaseEventData eventData)
{ {
if (highlight) button.OnPointerEnter(new PointerEventData(_system));
button.OnPointerClick(new PointerEventData(_system));
system = EventSystemManager.currentSystem; if (highlight) Invoke("RemoveHighlight", highlightDuration);
}
field = GetComponent<InputField>(); }
field.onSubmit.AddListener(new UnityEngine.Events.UnityAction<string>(OnSubmitField));
}
void OnSubmitField(string value)
{
if (highlight) button.OnPointerEnter(new PointerEventData(system));
button.OnPointerClick(new PointerEventData(system));
if (highlight) Invoke("RemoveHighlight", highlightDuration);
}
void RemoveHighlight()
{
button.OnPointerExit(new PointerEventData(system));
}
} }

View File

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

View File

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

View File

@ -3,76 +3,93 @@
/// Updated Credit BenZed /// Updated Credit BenZed
/// Sourced from - http://forum.unity3d.com/threads/color-picker.267043/ /// Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UI.Extensions;
using System.Collections;
public class ExampleSelectable : MonoBehaviour, IBoxSelectable { namespace UnityEngine.UI.Extensions
{
public class ExampleSelectable : MonoBehaviour, IBoxSelectable
{
#region Implemented members of IBoxSelectable #region Implemented members of IBoxSelectable
bool _selected = false; bool _selected = false;
public bool selected { public bool selected
get { {
return _selected; get
} {
return _selected;
}
set { set
_selected = value; {
} _selected = value;
} }
}
bool _preSelected = false; bool _preSelected = false;
public bool preSelected { public bool preSelected
get { {
return _preSelected; get
} {
return _preSelected;
}
set { set
_preSelected = value; {
} _preSelected = value;
} }
#endregion }
#endregion
//We want the test object to be either a UI element, a 2D element or a 3D element, so we'll get the appropriate components //We want the test object to be either a UI element, a 2D element or a 3D element, so we'll get the appropriate components
SpriteRenderer spriteRenderer; SpriteRenderer spriteRenderer;
Image image; Image image;
Text text; Text text;
void Start () { void Start()
spriteRenderer = transform.GetComponent<SpriteRenderer>(); {
image = transform.GetComponent<Image>(); spriteRenderer = transform.GetComponent<SpriteRenderer>();
text = transform.GetComponent<Text>(); image = transform.GetComponent<Image>();
} text = transform.GetComponent<Text>();
}
void Update () { void Update()
{
//What the game object does with the knowledge that it is selected is entirely up to it. //What the game object does with the knowledge that it is selected is entirely up to it.
//In this case we're just going to change the color. //In this case we're just going to change the color.
//White if deselected. //White if deselected.
Color color = Color.white; Color color = Color.white;
if (preSelected) { if (preSelected)
//Yellow if preselected {
color = Color.yellow; //Yellow if preselected
} color = Color.yellow;
if (selected) { }
//And green if selected. if (selected)
color = Color.green; {
} //And green if selected.
color = Color.green;
}
//Set the color depending on what the game object has. //Set the color depending on what the game object has.
if (spriteRenderer) { if (spriteRenderer)
spriteRenderer.color = color; {
} else if (text) { spriteRenderer.color = color;
text.color = color; }
} else if (image) { else if (text)
image.color = color; {
} else if (renderer) { text.color = color;
renderer.material.color = color; }
} else if (image)
{
image.color = color;
}
else if (renderer)
{
renderer.material.color = color;
}
} }
}
} }

View File

@ -3,11 +3,9 @@
///Updated Credit BenZed ///Updated Credit BenZed
///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/ ///Sourced from - http://forum.unity3d.com/threads/color-picker.267043/
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
namespace UnityEngine.UI.Extensions { namespace UnityEngine.UI.Extensions
{
/* /*
* Implement this interface on any MonoBehaviour that you'd like to be considered selectable. * Implement this interface on any MonoBehaviour that you'd like to be considered selectable.

View File

@ -26,16 +26,13 @@
* *
*/ */
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine.Events;
namespace UnityEngine.UI.Extensions
namespace UnityEngine.UI.Extensions { {
[RequireComponent(typeof(Canvas))] [RequireComponent(typeof(Canvas))]
[AddComponentMenu("UI/Extensions/Selection Box")]
public class SelectionBox : MonoBehaviour public class SelectionBox : MonoBehaviour
{ {

View File

@ -5,63 +5,68 @@
/// - updated to support new semantics for EventSystem in later 4.6 builds /// - updated to support new semantics for EventSystem in later 4.6 builds
/// - autoselect "firstSelectedGameObject" since it doesn't seem to work automatically /// - autoselect "firstSelectedGameObject" since it doesn't seem to work automatically
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
using System.Collections;
public class TabNavigationHelper : MonoBehaviour namespace UnityEngine.UI.Extensions
{ {
private EventSystem _system; [RequireComponent(typeof(EventSystem))]
[AddComponentMenu("Event/Extensions/Tab Navigation Helper")]
void Start() public class TabNavigationHelper : MonoBehaviour
{ {
_system = EventSystem.current; private EventSystem _system;
}
public void Update() void Start()
{
Selectable next = null;
if (Input.GetKeyDown(KeyCode.Tab) && Input.GetKey(KeyCode.LeftShift))
{ {
if (_system.currentSelectedGameObject != null) _system = GetComponent<EventSystem>();
if (_system == null)
{ {
next = _system.currentSelectedGameObject.GetComponent<Selectable>().FindSelectableOnUp(); Debug.LogError("Needs to be attached to the Event System component in the scene");
} }
else }
public void Update()
{
Selectable next = null;
if (Input.GetKeyDown(KeyCode.Tab) && Input.GetKey(KeyCode.LeftShift))
{
if (_system.currentSelectedGameObject != null)
{
next = _system.currentSelectedGameObject.GetComponent<Selectable>().FindSelectableOnUp();
}
else
{
next = _system.firstSelectedGameObject.GetComponent<Selectable>();
}
}
else if (Input.GetKeyDown(KeyCode.Tab))
{
if (_system.currentSelectedGameObject != null)
{
next = _system.currentSelectedGameObject.GetComponent<Selectable>().FindSelectableOnDown();
}
else
{
next = _system.firstSelectedGameObject.GetComponent<Selectable>();
}
}
else if (_system.currentSelectedGameObject == null)
{ {
next = _system.firstSelectedGameObject.GetComponent<Selectable>(); next = _system.firstSelectedGameObject.GetComponent<Selectable>();
} }
selectGameObject(next);
} }
else if (Input.GetKeyDown(KeyCode.Tab))
private void selectGameObject(Selectable selectable)
{ {
if (_system.currentSelectedGameObject != null) if (selectable != null)
{ {
next = _system.currentSelectedGameObject.GetComponent<Selectable>().FindSelectableOnDown(); InputField inputfield = selectable.GetComponent<InputField>();
if (inputfield != null) inputfield.OnPointerClick(new PointerEventData(_system)); //if it's an input field, also set the text caret
_system.SetSelectedGameObject(selectable.gameObject, new BaseEventData(_system));
} }
else
{
next = _system.firstSelectedGameObject.GetComponent<Selectable>();
}
}
else if (_system.currentSelectedGameObject == null)
{
next = _system.firstSelectedGameObject.GetComponent<Selectable>();
}
selectGameObject(next);
}
private void selectGameObject(Selectable selectable)
{
if (selectable != null)
{
InputField inputfield = selectable.GetComponent<InputField>();
if (inputfield != null) inputfield.OnPointerClick(new PointerEventData(_system)); //if it's an input field, also set the text caret
_system.SetSelectedGameObject(selectable.gameObject, new BaseEventData(_system));
} }
} }
} }

View File

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

View File

@ -1,5 +1,7 @@
/// Credit drHogan /// Credit drHogan
/// Sourced from - http://forum.unity3d.com/threads/screenspace-camera-tooltip-controller-sweat-and-tears.293991/#post-1938929 /// Sourced from - http://forum.unity3d.com/threads/screenspace-camera-tooltip-controller-sweat-and-tears.293991/#post-1938929
/// updated ddreaper - refactored code to be more performant.
/// *Note - only works for Screenspace Camera canvases at present, needs updating to include Screenspace and Worldspace!
//ToolTip is written by Emiliano Pastorelli, H&R Tallinn (Estonia), http://www.hammerandravens.com //ToolTip is written by Emiliano Pastorelli, H&R Tallinn (Estonia), http://www.hammerandravens.com
//Copyright (c) 2015 Emiliano Pastorelli, H&R - Hammer&Ravens, Tallinn, Estonia. //Copyright (c) 2015 Emiliano Pastorelli, H&R - Hammer&Ravens, Tallinn, Estonia.
@ -17,144 +19,150 @@
//IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED //IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
using UnityEngine; namespace UnityEngine.UI.Extensions
using System.Collections; {
using UnityEngine.UI; [RequireComponent(typeof(RectTransform))]
[AddComponentMenu("UI/Extensions/Tooltip")]
public class ToolTip : MonoBehaviour
{
//text of the tooltip
private Text _text;
private RectTransform _rectTransform;
public class ToolTip : MonoBehaviour { //if the tooltip is inside a UI element
private bool _inside;
//text of the tooltip private bool _xShifted, _yShifted = false;
public Text text;
//if the tooltip is inside a UI element private float width, height, canvasWidth, canvasHeight;
bool inside;
bool xShifted = false; private int screenWidth, screenHeight;
bool yShifted = false;
int textLength; private float YShift,xShift;
public float width; private RenderMode _guiMode;
public float height;
int screenWidth; private Camera _guiCamera;
int screenHeight;
float canvasWidth; // Use this for initialization
float canvasHeight; public void Awake()
{
var _canvas = GetComponentInParent<Canvas>();
_guiCamera = _canvas.worldCamera;
_guiMode = _canvas.renderMode;
_rectTransform = GetComponent<RectTransform>();
public float yShift; _text = GetComponentInChildren<Text>();
public float xShift;
int canvasMode; _inside = false;
RenderMode GUIMode; //size of the screen
screenWidth = Screen.width;
screenHeight = Screen.height;
Camera GUICamera; xShift = 0f;
YShift = -30f;
// Use this for initialization _xShifted = _yShifted = false;
public void Awake () {
GUICamera = GameObject.Find("GUICamera").GetComponent<Camera>();
text = this.gameObject.GetComponentInChildren<Text>(); this.gameObject.SetActive(false);
inside=false; }
//size of the screen //Call this function externally to set the text of the template and activate the tooltip
screenWidth = Screen.width; public void SetTooltip(string ttext)
screenHeight = Screen.height; {
xShift = 0f; if (_guiMode == RenderMode.ScreenSpaceCamera)
yShift = -30f; {
//set the text and fit the tooltip panel to the text size
_text.text = ttext;
xShifted=yShifted=false; _rectTransform.sizeDelta = new Vector2(_text.preferredWidth + 40f, _text.preferredHeight + 25f);
GUIMode = this.transform.parent.GetComponent<Canvas>().renderMode; OnScreenSpaceCamera();
this.gameObject.SetActive(false); }
}
} //call this function on mouse exit to deactivate the template
public void HideTooltip()
{
if (_guiMode == RenderMode.ScreenSpaceCamera)
{
this.gameObject.SetActive(false);
_inside = false;
}
}
//Call this function externally to set the text of the template and activate the tooltip // Update is called once per frame
public void SetTooltip(string ttext){ void FixedUpdate()
{
if (_inside)
{
if (_guiMode == RenderMode.ScreenSpaceCamera)
{
OnScreenSpaceCamera();
}
}
}
if(GUIMode==RenderMode.ScreenSpaceCamera){ //main tooltip edge of screen guard and movement
//set the text and fit the tooltip panel to the text size public void OnScreenSpaceCamera()
text.text=ttext; {
Vector3 newPos = _guiCamera.ScreenToViewportPoint(Input.mousePosition - new Vector3(xShift, YShift, 0f));
Vector3 newPosWVP = _guiCamera.ViewportToWorldPoint(newPos);
this.transform.GetComponent<RectTransform>().sizeDelta = new Vector2(text.preferredWidth+40f,text.preferredHeight+25f); width = _rectTransform.sizeDelta[0];
height = _rectTransform.sizeDelta[1];
OnScreenSpaceCamera(); // check and solve problems for the tooltip that goes out of the screen on the horizontal axis
float val;
} Vector3 lowerLeft = _guiCamera.ViewportToWorldPoint(new Vector3(0.0f, 0.0f, 0.0f));
} Vector3 upperRight = _guiCamera.ViewportToWorldPoint(new Vector3(1.0f, 1.0f, 0.0f));
//call this function on mouse exit to deactivate the template //check for right edge of screen
public void HideTooltip(){ val = (newPosWVP.x + width / 2);
if(GUIMode==RenderMode.ScreenSpaceCamera){ if (val > upperRight.x)
this.gameObject.SetActive(false); {
inside=false; Vector3 shifter = new Vector3(val - upperRight.x, 0f, 0f);
} Vector3 newWorldPos = new Vector3(newPosWVP.x - shifter.x, newPos.y, 0f);
} newPos.x = _guiCamera.WorldToViewportPoint(newWorldPos).x;
}
//check for left edge of screen
val = (newPosWVP.x - width / 2);
if (val < lowerLeft.x)
{
Vector3 shifter = new Vector3(lowerLeft.x - val, 0f, 0f);
Vector3 newWorldPos = new Vector3(newPosWVP.x + shifter.x, newPos.y, 0f);
newPos.x = _guiCamera.WorldToViewportPoint(newWorldPos).x;
}
// Update is called once per frame // check and solve problems for the tooltip that goes out of the screen on the vertical axis
void FixedUpdate () {
if(inside){
if(GUIMode==RenderMode.ScreenSpaceCamera){
OnScreenSpaceCamera();
}
}
}
//main tooltip edge of screen guard and movement //check for upper edge of the screen
public void OnScreenSpaceCamera(){ val = (newPosWVP.y + height / 2);
Vector3 newPos = GUICamera.ScreenToViewportPoint(Input.mousePosition-new Vector3(xShift,yShift,0f)); if (val > upperRight.y)
{
Vector3 shifter = new Vector3(0f, 35f + height / 2, 0f);
Vector3 newWorldPos = new Vector3(newPos.x, newPosWVP.y - shifter.y, 0f);
newPos.y = _guiCamera.WorldToViewportPoint(newWorldPos).y;
}
width = this.transform.GetComponent<RectTransform>().sizeDelta[0]; //check for lower edge of the screen (if the shifts of the tooltip are kept as in this code, no need for this as the tooltip always appears above the mouse bu default)
height = this.transform.GetComponent<RectTransform>().sizeDelta[1]; val = (newPosWVP.y - height / 2);
if (val < lowerLeft.y)
{
Vector3 shifter = new Vector3(0f, 35f + height / 2, 0f);
Vector3 newWorldPos = new Vector3(newPos.x, newPosWVP.y + shifter.y, 0f);
newPos.y = _guiCamera.WorldToViewportPoint(newWorldPos).y;
}
// check and solve problems for the tooltip that goes out of the screen on the horizontal axis this.transform.position = new Vector3(newPosWVP.x, newPosWVP.y, 0f);
float val; this.gameObject.SetActive(true);
_inside = true;
Vector3 lowerLeft = GUICamera.ViewportToWorldPoint(new Vector3(0.0f,0.0f,0.0f)); }
Vector3 upperRight = GUICamera.ViewportToWorldPoint(new Vector3(1.0f,1.0f,0.0f)); }
//check for right edge of screen
val = (GUICamera.ViewportToWorldPoint(newPos).x+width/2);
if(val>upperRight.x){
Vector3 shifter = new Vector3(val-upperRight.x,0f,0f);
Vector3 newWorldPos = new Vector3(GUICamera.ViewportToWorldPoint(newPos).x-shifter.x,newPos.y,0f);
newPos.x = GUICamera.WorldToViewportPoint(newWorldPos).x;
}
//check for left edge of screen
val = (GUICamera.ViewportToWorldPoint(newPos).x-width/2);
if(val<lowerLeft.x){
Vector3 shifter = new Vector3(lowerLeft.x-val,0f,0f);
Vector3 newWorldPos = new Vector3(GUICamera.ViewportToWorldPoint(newPos).x+shifter.x,newPos.y,0f);
newPos.x = GUICamera.WorldToViewportPoint(newWorldPos).x;
}
// check and solve problems for the tooltip that goes out of the screen on the vertical axis
//check for upper edge of the screen
val = (GUICamera.ViewportToWorldPoint(newPos).y+height/2);
if(val>upperRight.y){
Vector3 shifter = new Vector3(0f,35f+height/2,0f);
Vector3 newWorldPos = new Vector3(newPos.x,GUICamera.ViewportToWorldPoint(newPos).y-shifter.y,0f);
newPos.y = GUICamera.WorldToViewportPoint(newWorldPos).y;
}
//check for lower edge of the screen (if the shifts of the tooltip are kept as in this code, no need for this as the tooltip always appears above the mouse bu default)
val = (GUICamera.ViewportToWorldPoint(newPos).y-height/2);
if(val<lowerLeft.y){
Vector3 shifter = new Vector3(0f,35f+height/2,0f);
Vector3 newWorldPos = new Vector3(newPos.x,GUICamera.ViewportToWorldPoint(newPos).y+shifter.y,0f);
newPos.y = GUICamera.WorldToViewportPoint(newWorldPos).y;
}
this.transform.position= new Vector3(GUICamera.ViewportToWorldPoint(newPos).x,GUICamera.ViewportToWorldPoint(newPos).y,0f);
this.gameObject.SetActive(true);
inside=true;
}
} }

8
Scripts/ToolTip.cs.meta Normal file
View File

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

View File

@ -1,61 +1,58 @@
/// Credit AriathTheWise /// Credit AriathTheWise
/// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1796783 /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1796783
using UnityEngine;
using UnityEngine.Events; using UnityEngine.Events;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections;
namespace UnityEngine.UI.Extensions
/// <summary>
/// UIButton
/// </summary>
public class UIButton : Button, IPointerDownHandler, IPointerUpHandler
{ {
#region Sub-Classes /// <summary>
[System.Serializable] /// UIButton
public class UIButtonEvent : UnityEvent<PointerEventData.InputButton> { } /// </summary>
#endregion [AddComponentMenu("UI/Extensions/UI Button")]
public class UIButton : Button, IPointerDownHandler, IPointerUpHandler
#region Events
public UIButtonEvent OnButtonClick;
public UIButtonEvent OnButtonPress;
public UIButtonEvent OnButtonRelease;
#endregion
public override void OnPointerClick(PointerEventData eventData)
{ {
base.OnSubmit(eventData); #region Sub-Classes
[System.Serializable]
public class UIButtonEvent : UnityEvent<PointerEventData.InputButton> { }
#endregion
if (OnButtonClick != null) #region Events
public UIButtonEvent OnButtonClick;
public UIButtonEvent OnButtonPress;
public UIButtonEvent OnButtonRelease;
#endregion
public override void OnPointerClick(PointerEventData eventData)
{ {
OnButtonClick.Invoke(eventData.button); base.OnSubmit(eventData);
if (OnButtonClick != null)
{
OnButtonClick.Invoke(eventData.button);
}
} }
}
void IPointerDownHandler.OnPointerDown (PointerEventData eventData) void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
{
DoStateTransition(SelectionState.Pressed, false);
if (OnButtonPress != null)
{ {
OnButtonPress.Invoke(eventData.button); DoStateTransition(SelectionState.Pressed, false);
if (OnButtonPress != null)
{
OnButtonPress.Invoke(eventData.button);
}
} }
}
void IPointerUpHandler.OnPointerUp (PointerEventData eventData) void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
{
DoStateTransition(SelectionState.Normal, false);
if (OnButtonRelease != null)
{ {
OnButtonRelease.Invoke(eventData.button); DoStateTransition(SelectionState.Normal, false);
if (OnButtonRelease != null)
{
OnButtonRelease.Invoke(eventData.button);
}
} }
} }
} }

8
Scripts/UIButton.cs.meta Normal file
View File

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

View File

@ -1,15 +1,14 @@
/// Credit ChoMPHi /// Credit ChoMPHi
/// Sourced from - http://forum.unity3d.com/threads/script-flippable-for-ui-graphics.291711/ /// Sourced from - http://forum.unity3d.com/threads/script-flippable-for-ui-graphics.291711/
using UnityEngine;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
namespace UnityEngine.UI namespace UnityEngine.UI.Extensions
{ {
[RequireComponent(typeof(RectTransform)), RequireComponent(typeof(Graphic)), DisallowMultipleComponent, AddComponentMenu("UI/Flippable")] [RequireComponent(typeof(RectTransform), typeof(Graphic)), DisallowMultipleComponent]
public class UIFlippable : MonoBehaviour, IVertexModifier { [AddComponentMenu("UI/Effects/Extensions/Flippable")]
public class UIFlippable : MonoBehaviour, IVertexModifier
{
[SerializeField] private bool m_Horizontal = false; [SerializeField] private bool m_Horizontal = false;
[SerializeField] private bool m_Veritical = false; [SerializeField] private bool m_Veritical = false;

View File

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

View File

@ -6,104 +6,109 @@
using System; using System;
using UnityEngine;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
/// <summary> namespace UnityEngine.UI.Extensions
/// Includes a few fixes of my own, mainly to tidy up duplicates, remove unneeded stuff and testing. (nothing major, all the crew above did the hard work!)
/// </summary>
public class UIWindowBase : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{ {
RectTransform m_transform = null; /// <summary>
private bool _isDragging = false; /// Includes a few fixes of my own, mainly to tidy up duplicates, remove unneeded stuff and testing. (nothing major, all the crew above did the hard work!)
public static bool ResetCoords = false; /// </summary>
private Vector3 m_originalCoods = Vector3.zero; [RequireComponent(typeof(RectTransform))]
private Canvas m_canvas; [AddComponentMenu("UI/Extensions/UI Window Base")]
private RectTransform m_canvasRectTransform; public class UIWindowBase : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
public int KeepWindowInCanvas = 5; // # of pixels of the window that must stay inside the canvas view.
// Use this for initialization
void Start () {
m_transform = GetComponent<RectTransform>();
m_originalCoods = m_transform.position;
m_canvas = GetComponentInParent<Canvas>();
m_canvasRectTransform = m_canvas.GetComponent<RectTransform>();
}
void Update(){
if (ResetCoords)
resetCoordinatePosition();
}
public void OnDrag(PointerEventData eventData)
{ {
if (_isDragging) RectTransform m_transform = null;
{ private bool _isDragging = false;
var delta = ScreenToCanvas(eventData.position) - ScreenToCanvas(eventData.position - eventData.delta); public static bool ResetCoords = false;
m_transform.localPosition += delta; private Vector3 m_originalCoods = Vector3.zero;
} private Canvas m_canvas;
} private RectTransform m_canvasRectTransform;
public int KeepWindowInCanvas = 5; // # of pixels of the window that must stay inside the canvas view.
//Note, the begin drag and end drag aren't actually needed to control the drag. However, I'd recommend keeping it in case you want to do somethind else when draggging starts and stops // Use this for initialization
public void OnBeginDrag(PointerEventData eventData) void Start()
{
if (eventData.pointerCurrentRaycast.gameObject == null)
return;
if (eventData.pointerCurrentRaycast.gameObject.name == name)
{ {
_isDragging = true; m_transform = GetComponent<RectTransform>();
m_originalCoods = m_transform.position;
m_canvas = GetComponentInParent<Canvas>();
m_canvasRectTransform = m_canvas.GetComponent<RectTransform>();
} }
}
public void OnEndDrag(PointerEventData eventData) void Update()
{
_isDragging = false;
}
void resetCoordinatePosition()
{
m_transform.position = m_originalCoods;
ResetCoords = false;
}
private Vector3 ScreenToCanvas(Vector3 screenPosition)
{
Vector3 localPosition;
Vector2 min;
Vector2 max;
var canvasSize = m_canvasRectTransform.sizeDelta;
if (m_canvas.renderMode == RenderMode.ScreenSpaceOverlay || (m_canvas.renderMode == RenderMode.ScreenSpaceCamera && m_canvas.worldCamera == null))
{ {
localPosition = screenPosition; if (ResetCoords)
resetCoordinatePosition();
min = Vector2.zero;
max = canvasSize;
} }
else
{
var ray = m_canvas.worldCamera.ScreenPointToRay(screenPosition);
var plane = new Plane(m_canvasRectTransform.forward, m_canvasRectTransform.position);
float distance; public void OnDrag(PointerEventData eventData)
if (plane.Raycast(ray, out distance) == false) {
if (_isDragging)
{ {
throw new Exception("Is it practically possible?"); var delta = ScreenToCanvas(eventData.position) - ScreenToCanvas(eventData.position - eventData.delta);
}; m_transform.localPosition += delta;
var worldPosition = ray.origin + ray.direction * distance; }
localPosition = m_canvasRectTransform.InverseTransformPoint(worldPosition);
min = -Vector2.Scale(canvasSize, m_canvasRectTransform.pivot);
max = Vector2.Scale(canvasSize, Vector2.one - m_canvasRectTransform.pivot);
} }
// keep window inside canvas //Note, the begin drag and end drag aren't actually needed to control the drag. However, I'd recommend keeping it in case you want to do somethind else when draggging starts and stops
localPosition.x = Mathf.Clamp(localPosition.x, min.x + KeepWindowInCanvas, max.x - KeepWindowInCanvas); public void OnBeginDrag(PointerEventData eventData)
localPosition.y = Mathf.Clamp(localPosition.y, min.y + KeepWindowInCanvas, max.y - KeepWindowInCanvas); {
return localPosition; if (eventData.pointerCurrentRaycast.gameObject == null)
return;
if (eventData.pointerCurrentRaycast.gameObject.name == name)
{
_isDragging = true;
}
}
public void OnEndDrag(PointerEventData eventData)
{
_isDragging = false;
}
void resetCoordinatePosition()
{
m_transform.position = m_originalCoods;
ResetCoords = false;
}
private Vector3 ScreenToCanvas(Vector3 screenPosition)
{
Vector3 localPosition;
Vector2 min;
Vector2 max;
var canvasSize = m_canvasRectTransform.sizeDelta;
if (m_canvas.renderMode == RenderMode.ScreenSpaceOverlay || (m_canvas.renderMode == RenderMode.ScreenSpaceCamera && m_canvas.worldCamera == null))
{
localPosition = screenPosition;
min = Vector2.zero;
max = canvasSize;
}
else
{
var ray = m_canvas.worldCamera.ScreenPointToRay(screenPosition);
var plane = new Plane(m_canvasRectTransform.forward, m_canvasRectTransform.position);
float distance;
if (plane.Raycast(ray, out distance) == false)
{
throw new Exception("Is it practically possible?");
};
var worldPosition = ray.origin + ray.direction * distance;
localPosition = m_canvasRectTransform.InverseTransformPoint(worldPosition);
min = -Vector2.Scale(canvasSize, m_canvasRectTransform.pivot);
max = Vector2.Scale(canvasSize, Vector2.one - m_canvasRectTransform.pivot);
}
// keep window inside canvas
localPosition.x = Mathf.Clamp(localPosition.x, min.x + KeepWindowInCanvas, max.x - KeepWindowInCanvas);
localPosition.y = Mathf.Clamp(localPosition.y, min.y + KeepWindowInCanvas, max.y - KeepWindowInCanvas);
return localPosition;
}
} }
} }

View File

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

View File

@ -2,98 +2,114 @@
/// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/ (uGUITools link) /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/ (uGUITools link)
using UnityEditor; using UnityEditor;
using UnityEngine; namespace UnityEngine.UI.Extensions
{
public class uGUITools : MonoBehaviour
{
[MenuItem("uGUI/Anchors to Corners %[")]
static void AnchorsToCorners()
{
foreach (Transform transform in Selection.transforms)
{
RectTransform t = transform as RectTransform;
RectTransform pt = Selection.activeTransform.parent as RectTransform;
public class uGUITools : MonoBehaviour { if (t == null || pt == null) return;
[MenuItem("uGUI/Anchors to Corners %[")]
static void AnchorsToCorners(){
foreach(Transform transform in Selection.transforms){
RectTransform t = transform as RectTransform;
RectTransform pt = Selection.activeTransform.parent as RectTransform;
if(t == null || pt == null) return; Vector2 newAnchorsMin = new Vector2(t.anchorMin.x + t.offsetMin.x / pt.rect.width,
t.anchorMin.y + t.offsetMin.y / pt.rect.height);
Vector2 newAnchorsMax = new Vector2(t.anchorMax.x + t.offsetMax.x / pt.rect.width,
t.anchorMax.y + t.offsetMax.y / pt.rect.height);
Vector2 newAnchorsMin = new Vector2(t.anchorMin.x + t.offsetMin.x / pt.rect.width, t.anchorMin = newAnchorsMin;
t.anchorMin.y + t.offsetMin.y / pt.rect.height); t.anchorMax = newAnchorsMax;
Vector2 newAnchorsMax = new Vector2(t.anchorMax.x + t.offsetMax.x / pt.rect.width, t.offsetMin = t.offsetMax = new Vector2(0, 0);
t.anchorMax.y + t.offsetMax.y / pt.rect.height); }
}
t.anchorMin = newAnchorsMin; [MenuItem("uGUI/Corners to Anchors %]")]
t.anchorMax = newAnchorsMax; static void CornersToAnchors()
t.offsetMin = t.offsetMax = new Vector2(0, 0); {
} foreach (Transform transform in Selection.transforms)
} {
RectTransform t = transform as RectTransform;
[MenuItem("uGUI/Corners to Anchors %]")] if (t == null) return;
static void CornersToAnchors(){
foreach(Transform transform in Selection.transforms){
RectTransform t = transform as RectTransform;
if(t == null) return; t.offsetMin = t.offsetMax = new Vector2(0, 0);
}
}
t.offsetMin = t.offsetMax = new Vector2(0, 0); [MenuItem("uGUI/Mirror Horizontally Around Anchors %;")]
} static void MirrorHorizontallyAnchors()
} {
MirrorHorizontally(false);
}
[MenuItem("uGUI/Mirror Horizontally Around Anchors %;")] [MenuItem("uGUI/Mirror Horizontally Around Parent Center %:")]
static void MirrorHorizontallyAnchors(){ static void MirrorHorizontallyParent()
MirrorHorizontally(false); {
} MirrorHorizontally(true);
}
[MenuItem("uGUI/Mirror Horizontally Around Parent Center %:")] static void MirrorHorizontally(bool mirrorAnchors)
static void MirrorHorizontallyParent(){ {
MirrorHorizontally(true); foreach (Transform transform in Selection.transforms)
} {
RectTransform t = transform as RectTransform;
RectTransform pt = Selection.activeTransform.parent as RectTransform;
static void MirrorHorizontally(bool mirrorAnchors){ if (t == null || pt == null) return;
foreach(Transform transform in Selection.transforms){
RectTransform t = transform as RectTransform;
RectTransform pt = Selection.activeTransform.parent as RectTransform;
if(t == null || pt == null) return; if (mirrorAnchors)
{
Vector2 oldAnchorMin = t.anchorMin;
t.anchorMin = new Vector2(1 - t.anchorMax.x, t.anchorMin.y);
t.anchorMax = new Vector2(1 - oldAnchorMin.x, t.anchorMax.y);
}
if(mirrorAnchors){ Vector2 oldOffsetMin = t.offsetMin;
Vector2 oldAnchorMin = t.anchorMin; t.offsetMin = new Vector2(-t.offsetMax.x, t.offsetMin.y);
t.anchorMin = new Vector2(1 - t.anchorMax.x, t.anchorMin.y); t.offsetMax = new Vector2(-oldOffsetMin.x, t.offsetMax.y);
t.anchorMax = new Vector2(1 - oldAnchorMin.x, t.anchorMax.y);
}
Vector2 oldOffsetMin = t.offsetMin; t.localScale = new Vector3(-t.localScale.x, t.localScale.y, t.localScale.z);
t.offsetMin = new Vector2(-t.offsetMax.x, t.offsetMin.y); }
t.offsetMax = new Vector2(-oldOffsetMin.x, t.offsetMax.y); }
t.localScale = new Vector3(-t.localScale.x, t.localScale.y, t.localScale.z); [MenuItem("uGUI/Mirror Vertically Around Anchors %'")]
} static void MirrorVerticallyAnchors()
} {
MirrorVertically(false);
}
[MenuItem("uGUI/Mirror Vertically Around Anchors %'")] [MenuItem("uGUI/Mirror Vertically Around Parent Center %\"")]
static void MirrorVerticallyAnchors(){ static void MirrorVerticallyParent()
MirrorVertically(false); {
} MirrorVertically(true);
}
[MenuItem("uGUI/Mirror Vertically Around Parent Center %\"")] static void MirrorVertically(bool mirrorAnchors)
static void MirrorVerticallyParent(){ {
MirrorVertically(true); foreach (Transform transform in Selection.transforms)
} {
RectTransform t = transform as RectTransform;
RectTransform pt = Selection.activeTransform.parent as RectTransform;
static void MirrorVertically(bool mirrorAnchors){ if (t == null || pt == null) return;
foreach(Transform transform in Selection.transforms){
RectTransform t = transform as RectTransform;
RectTransform pt = Selection.activeTransform.parent as RectTransform;
if(t == null || pt == null) return; if (mirrorAnchors)
{
Vector2 oldAnchorMin = t.anchorMin;
t.anchorMin = new Vector2(t.anchorMin.x, 1 - t.anchorMax.y);
t.anchorMax = new Vector2(t.anchorMax.x, 1 - oldAnchorMin.y);
}
if(mirrorAnchors){ Vector2 oldOffsetMin = t.offsetMin;
Vector2 oldAnchorMin = t.anchorMin; t.offsetMin = new Vector2(t.offsetMin.x, -t.offsetMax.y);
t.anchorMin = new Vector2(t.anchorMin.x, 1 - t.anchorMax.y); t.offsetMax = new Vector2(t.offsetMax.x, -oldOffsetMin.y);
t.anchorMax = new Vector2(t.anchorMax.x, 1 - oldAnchorMin.y);
}
Vector2 oldOffsetMin = t.offsetMin; t.localScale = new Vector3(t.localScale.x, -t.localScale.y, t.localScale.z);
t.offsetMin = new Vector2(t.offsetMin.x, -t.offsetMax.y); }
t.offsetMax = new Vector2(t.offsetMax.x, -oldOffsetMin.y); }
}
t.localScale = new Vector3(t.localScale.x, -t.localScale.y, t.localScale.z);
}
}
} }

View File

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