code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Unity doesn't keep the values of static variables after scripts change get recompiled. One way around this
/// is to store the references in EditorPrefs -- retrieve them at start, and save them whenever something changes.
/// </summary>
public class NGUISettings
{
public enum ColorMode
{
Orange,
Green,
Blue,
}
#region Generic Get and Set methods
/// <summary>
/// Save the specified boolean value in settings.
/// </summary>
static public void SetBool (string name, bool val) { EditorPrefs.SetBool(name, val); }
/// <summary>
/// Save the specified integer value in settings.
/// </summary>
static public void SetInt (string name, int val) { EditorPrefs.SetInt(name, val); }
/// <summary>
/// Save the specified float value in settings.
/// </summary>
static public void SetFloat (string name, float val) { EditorPrefs.SetFloat(name, val); }
/// <summary>
/// Save the specified string value in settings.
/// </summary>
static public void SetString (string name, string val) { EditorPrefs.SetString(name, val); }
/// <summary>
/// Save the specified color value in settings.
/// </summary>
static public void SetColor (string name, Color c) { SetString(name, c.r + " " + c.g + " " + c.b + " " + c.a); }
/// <summary>
/// Save the specified enum value to settings.
/// </summary>
static public void SetEnum (string name, System.Enum val) { SetString(name, val.ToString()); }
/// <summary>
/// Save the specified object in settings.
/// </summary>
static public void Set (string name, Object obj)
{
if (obj == null)
{
EditorPrefs.DeleteKey(name);
}
else
{
if (obj != null)
{
string path = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(path))
{
EditorPrefs.SetString(name, path);
}
else
{
EditorPrefs.SetString(name, obj.GetInstanceID().ToString());
}
}
else EditorPrefs.DeleteKey(name);
}
}
/// <summary>
/// Get the previously saved boolean value.
/// </summary>
static public bool GetBool (string name, bool defaultValue) { return EditorPrefs.GetBool(name, defaultValue); }
/// <summary>
/// Get the previously saved integer value.
/// </summary>
static public int GetInt (string name, int defaultValue) { return EditorPrefs.GetInt(name, defaultValue); }
/// <summary>
/// Get the previously saved float value.
/// </summary>
static public float GetFloat (string name, float defaultValue) { return EditorPrefs.GetFloat(name, defaultValue); }
/// <summary>
/// Get the previously saved string value.
/// </summary>
static public string GetString (string name, string defaultValue) { return EditorPrefs.GetString(name, defaultValue); }
/// <summary>
/// Get a previously saved color value.
/// </summary>
static public Color GetColor (string name, Color c)
{
string strVal = GetString(name, c.r + " " + c.g + " " + c.b + " " + c.a);
string[] parts = strVal.Split(' ');
if (parts.Length == 4)
{
float.TryParse(parts[0], out c.r);
float.TryParse(parts[1], out c.g);
float.TryParse(parts[2], out c.b);
float.TryParse(parts[3], out c.a);
}
return c;
}
/// <summary>
/// Get a previously saved enum from settings.
/// </summary>
static public T GetEnum<T> (string name, T defaultValue)
{
string val = GetString(name, defaultValue.ToString());
string[] names = System.Enum.GetNames(typeof(T));
System.Array values = System.Enum.GetValues(typeof(T));
for (int i = 0; i < names.Length; ++i)
{
if (names[i] == val)
return (T)values.GetValue(i);
}
return defaultValue;
}
/// <summary>
/// Get a previously saved object from settings.
/// </summary>
static public T Get<T> (string name, T defaultValue) where T : Object
{
string path = EditorPrefs.GetString(name);
if (string.IsNullOrEmpty(path)) return null;
T retVal = NGUIEditorTools.LoadAsset<T>(path);
if (retVal == null)
{
int id;
if (int.TryParse(path, out id))
return EditorUtility.InstanceIDToObject(id) as T;
}
return retVal;
}
#endregion
#region Convenience accessor properties
static public Color color
{
get { return GetColor("NGUI Color", Color.white); }
set { SetColor("NGUI Color", value); }
}
static public Color foregroundColor
{
get { return GetColor("NGUI FG Color", Color.white); }
set { SetColor("NGUI FG Color", value); }
}
static public Color backgroundColor
{
get { return GetColor("NGUI BG Color", Color.black); }
set { SetColor("NGUI BG Color", value); }
}
static public ColorMode colorMode
{
get { return GetEnum("NGUI Color Mode", ColorMode.Blue); }
set { SetEnum("NGUI Color Mode", value); }
}
static public Object ambigiousFont
{
get
{
Font fnt = Get<Font>("NGUI Dynamic Font", null);
if (fnt != null) return fnt;
return Get<UIFont>("NGUI Bitmap Font", null);
}
set
{
if (value == null)
{
Set("NGUI Bitmap Font", null);
Set("NGUI Dynamic Font", null);
}
else if (value is Font)
{
Set("NGUI Bitmap Font", null);
Set("NGUI Dynamic Font", value as Font);
}
else if (value is UIFont)
{
Set("NGUI Bitmap Font", value as UIFont);
Set("NGUI Dynamic Font", null);
}
}
}
static public UIAtlas atlas
{
get { return Get<UIAtlas>("NGUI Atlas", null); }
set { Set("NGUI Atlas", value); }
}
static public Texture texture
{
get { return Get<Texture>("NGUI Texture", null); }
set { Set("NGUI Texture", value); }
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
static public Sprite sprite2D
{
get { return Get<Sprite>("NGUI Sprite2D", null); }
set { Set("NGUI Sprite2D", value); }
}
#endif
static public string selectedSprite
{
get { return GetString("NGUI Sprite", null); }
set { SetString("NGUI Sprite", value); }
}
static public UIWidget.Pivot pivot
{
get { return GetEnum("NGUI Pivot", UIWidget.Pivot.Center); }
set { SetEnum("NGUI Pivot", value); }
}
static public int layer
{
get
{
int layer = GetInt("NGUI Layer", -1);
if (layer == -1) layer = LayerMask.NameToLayer("UI");
if (layer == -1) layer = LayerMask.NameToLayer("2D UI");
return (layer == -1) ? 9 : layer;
}
set
{
SetInt("NGUI Layer", value);
}
}
static public TextAsset fontData
{
get { return Get<TextAsset>("NGUI Font Data", null); }
set { Set("NGUI Font Data", value); }
}
static public Texture2D fontTexture
{
get { return Get<Texture2D>("NGUI Font Texture", null); }
set { Set("NGUI Font Texture", value); }
}
static public int fontSize
{
get { return GetInt("NGUI Font Size", 16); }
set { SetInt("NGUI Font Size", value); }
}
static public FontStyle fontStyle
{
get { return GetEnum("NGUI Font Style", FontStyle.Normal); }
set { SetEnum("NGUI Font Style", value); }
}
static public Font dynamicFont
{
get { return Get<Font>("NGUI Dynamic Font", null); }
set { Set("NGUI Dynamic Font", value); }
}
static public UILabel.Overflow overflowStyle
{
get { return GetEnum("NGUI Overflow", UILabel.Overflow.ShrinkContent); }
set { SetEnum("NGUI Overflow", value); }
}
static public string partialSprite
{
get { return GetString("NGUI Partial", null); }
set { SetString("NGUI Partial", value); }
}
static public int atlasPadding
{
get { return GetInt("NGUI Padding", 1); }
set { SetInt("NGUI Padding", value); }
}
static public bool atlasTrimming
{
get { return GetBool("NGUI Trim", true); }
set { SetBool("NGUI Trim", value); }
}
static public bool atlasPMA
{
get { return GetBool("NGUI PMA", false); }
set { SetBool("NGUI PMA", value); }
}
static public bool unityPacking
{
get { return GetBool("NGUI Packing", true); }
set { SetBool("NGUI Packing", value); }
}
static public bool forceSquareAtlas
{
get { return GetBool("NGUI Square", false); }
set { SetBool("NGUI Square", value); }
}
static public bool allow4096
{
get { return GetBool("NGUI 4096", true); }
set { SetBool("NGUI 4096", value); }
}
static public bool showAllDCs
{
get { return GetBool("NGUI DCs", true); }
set { SetBool("NGUI DCs", value); }
}
static public bool drawGuides
{
get { return GetBool("NGUI Guides", false); }
set { SetBool("NGUI Guides", value); }
}
static public string charsToInclude
{
get { return GetString("NGUI Chars", ""); }
set { SetString("NGUI Chars", value); }
}
static public string pathToFreeType
{
get
{
string path = Application.dataPath;
if (Application.platform == RuntimePlatform.WindowsEditor) path += "/NGUI/Editor/FreeType.dll";
else path += "/NGUI/Editor/FreeType.dylib";
return GetString("NGUI FreeType", path);
}
set { SetString("NGUI FreeType", value); }
}
#endregion
/// <summary>
/// Convenience method -- add a widget.
/// </summary>
static public UIWidget AddWidget (GameObject go)
{
UIWidget w = NGUITools.AddWidget<UIWidget>(go);
w.name = "Container";
w.pivot = pivot;
w.width = 100;
w.height = 100;
return w;
}
/// <summary>
/// Convenience method -- add a texture.
/// </summary>
static public UITexture AddTexture (GameObject go)
{
UITexture w = NGUITools.AddWidget<UITexture>(go);
w.name = "Texture";
w.pivot = pivot;
w.mainTexture = texture;
w.width = 100;
w.height = 100;
return w;
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
/// <summary>
/// Convenience method -- add a UnityEngine.Sprite.
/// </summary>
static public UI2DSprite Add2DSprite (GameObject go)
{
UI2DSprite w = NGUITools.AddWidget<UI2DSprite>(go);
w.name = "2D Sprite";
w.pivot = pivot;
w.sprite2D = sprite2D;
w.width = 100;
w.height = 100;
return w;
}
#endif
/// <summary>
/// Convenience method -- add a sprite.
/// </summary>
static public UISprite AddSprite (GameObject go)
{
UISprite w = NGUITools.AddWidget<UISprite>(go);
w.name = "Sprite";
w.atlas = atlas;
w.spriteName = selectedSprite;
if (w.atlas != null && !string.IsNullOrEmpty(w.spriteName))
{
UISpriteData sp = w.atlas.GetSprite(w.spriteName);
if (sp != null && sp.hasBorder)
w.type = UISprite.Type.Sliced;
}
w.pivot = pivot;
w.width = 100;
w.height = 100;
w.MakePixelPerfect();
return w;
}
/// <summary>
/// Convenience method -- add a label with default parameters.
/// </summary>
static public UILabel AddLabel (GameObject go)
{
UILabel w = NGUITools.AddWidget<UILabel>(go);
w.name = "Label";
w.ambigiousFont = ambigiousFont;
w.text = "New Label";
w.pivot = pivot;
w.width = 120;
w.height = Mathf.Max(20, GetInt("NGUI Font Height", 16));
w.fontStyle = fontStyle;
w.fontSize = fontSize;
w.applyGradient = true;
w.gradientBottom = new Color(0.7f, 0.7f, 0.7f);
w.AssumeNaturalSize();
return w;
}
/// <summary>
/// Convenience method -- add a new panel.
/// </summary>
static public UIPanel AddPanel (GameObject go)
{
if (go == null) return null;
int depth = UIPanel.nextUnusedDepth;
UIPanel panel = NGUITools.AddChild<UIPanel>(go);
panel.depth = depth;
return panel;
}
/// <summary>
/// Copy the specified widget's parameters.
/// </summary>
static public void CopyWidget (UIWidget widget)
{
SetInt("Width", widget.width);
SetInt("Height", widget.height);
SetInt("Depth", widget.depth);
SetColor("Widget Color", widget.color);
SetEnum("Widget Pivot", widget.pivot);
if (widget is UISprite) CopySprite(widget as UISprite);
else if (widget is UILabel) CopyLabel(widget as UILabel);
}
/// <summary>
/// Paste the specified widget's style.
/// </summary>
static public void PasteWidget (UIWidget widget, bool fully)
{
widget.color = GetColor("Widget Color", widget.color);
widget.pivot = GetEnum<UIWidget.Pivot>("Widget Pivot", widget.pivot);
if (fully)
{
widget.width = GetInt("Width", widget.width);
widget.height = GetInt("Height", widget.height);
widget.depth = GetInt("Depth", widget.depth);
}
if (widget is UISprite) PasteSprite(widget as UISprite, fully);
else if (widget is UILabel) PasteLabel(widget as UILabel, fully);
}
/// <summary>
/// Copy the specified sprite's style.
/// </summary>
static void CopySprite (UISprite sp)
{
SetString("Atlas", NGUIEditorTools.ObjectToGUID(sp.atlas));
SetString("Sprite", sp.spriteName);
SetEnum("Sprite Type", sp.type);
SetEnum("Left Type", sp.leftType);
SetEnum("Right Type", sp.rightType);
SetEnum("Top Type", sp.topType);
SetEnum("Bottom Type", sp.bottomType);
SetEnum("Center Type", sp.centerType);
SetFloat("Fill", sp.fillAmount);
SetEnum("FDir", sp.fillDirection);
}
/// <summary>
/// Copy the specified label's style.
/// </summary>
static void CopyLabel (UILabel lbl)
{
SetString("Font", NGUIEditorTools.ObjectToGUID(lbl.ambigiousFont));
SetInt("Font Size", lbl.fontSize);
SetEnum("Font Style", lbl.fontStyle);
SetEnum("Overflow", lbl.overflowMethod);
SetInt("SpacingX", lbl.spacingX);
SetInt("SpacingY", lbl.spacingY);
SetInt("MaxLines", lbl.maxLineCount);
SetBool("Encoding", lbl.supportEncoding);
SetBool("Gradient", lbl.applyGradient);
SetColor("Gradient B", lbl.gradientBottom);
SetColor("Gradient T", lbl.gradientTop);
SetEnum("Effect", lbl.effectStyle);
SetColor("Effect C", lbl.effectColor);
SetFloat("Effect X", lbl.effectDistance.x);
SetFloat("Effect Y", lbl.effectDistance.y);
}
/// <summary>
/// Paste the specified sprite's style.
/// </summary>
static void PasteSprite (UISprite sp, bool fully)
{
if (fully) sp.atlas = NGUIEditorTools.GUIDToObject<UIAtlas>(GetString("Atlas", null));
sp.spriteName = GetString("Sprite", sp.spriteName);
sp.type = GetEnum<UISprite.Type>("Sprite Type", sp.type);
sp.leftType = GetEnum<UISprite.AdvancedType>("Left Type", UISprite.AdvancedType.Sliced);
sp.rightType = GetEnum<UISprite.AdvancedType>("Right Type", UISprite.AdvancedType.Sliced);
sp.topType = GetEnum<UISprite.AdvancedType>("Top Type", UISprite.AdvancedType.Sliced);
sp.bottomType = GetEnum<UISprite.AdvancedType>("Bottom Type", UISprite.AdvancedType.Sliced);
sp.centerType = GetEnum<UISprite.AdvancedType>("Center Type", UISprite.AdvancedType.Sliced);
sp.fillAmount = GetFloat("Fill", sp.fillAmount);
sp.fillDirection = GetEnum<UISprite.FillDirection>("FDir", sp.fillDirection);
}
/// <summary>
/// Paste the specified label's style.
/// </summary>
static void PasteLabel (UILabel lbl, bool fully)
{
if (fully)
{
Object obj = NGUIEditorTools.GUIDToObject(GetString("Font", null));
if (obj != null)
{
if (obj.GetType() == typeof(Font))
{
lbl.ambigiousFont = obj as Font;
}
else if (obj.GetType() == typeof(GameObject))
{
lbl.ambigiousFont = (obj as GameObject).GetComponent<UIFont>();
}
}
lbl.fontSize = GetInt("Font Size", lbl.fontSize);
lbl.fontStyle = GetEnum<FontStyle>("Font Style", lbl.fontStyle);
}
lbl.overflowMethod = GetEnum<UILabel.Overflow>("Overflow", lbl.overflowMethod);
lbl.spacingX = GetInt("SpacingX", lbl.spacingX);
lbl.spacingY = GetInt("SpacingY", lbl.spacingY);
lbl.maxLineCount = GetInt("MaxLines", lbl.maxLineCount);
lbl.supportEncoding = GetBool("Encoding", lbl.supportEncoding);
lbl.applyGradient = GetBool("Gradient", lbl.applyGradient);
lbl.gradientBottom = GetColor("Gradient B", lbl.gradientBottom);
lbl.gradientTop = GetColor("Gradient T", lbl.gradientTop);
lbl.effectStyle = GetEnum<UILabel.Effect>("Effect", lbl.effectStyle);
lbl.effectColor = GetColor("Effect C", lbl.effectColor);
float x = GetFloat("Effect X", lbl.effectDistance.x);
float y = GetFloat("Effect Y", lbl.effectDistance.y);
lbl.effectDistance = new Vector2(x, y);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUISettings.cs
|
C#
|
asf20
| 15,891
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenColor))]
public class TweenColorEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenColor tw = target as TweenColor;
GUI.changed = false;
Color from = EditorGUILayout.ColorField("From", tw.from);
Color to = EditorGUILayout.ColorField("To", tw.to);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenColorEditor.cs
|
C#
|
asf20
| 766
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
/// <summary>
/// This script adds the NGUI menu options to the Unity Editor.
/// </summary>
static public class NGUIMenu
{
#region Selection
static public GameObject SelectedRoot () { return NGUIEditorTools.SelectedRoot(); }
[MenuItem("NGUI/Selection/Bring To Front &#=", false, 0)]
static public void BringForward2 ()
{
int val = 0;
for (int i = 0; i < Selection.gameObjects.Length; ++i)
val |= NGUITools.AdjustDepth(Selection.gameObjects[i], 1000);
if ((val & 1) != 0)
{
NGUITools.NormalizePanelDepths();
if (UIPanelTool.instance != null)
UIPanelTool.instance.Repaint();
}
if ((val & 2) != 0) NGUITools.NormalizeWidgetDepths();
}
[MenuItem("NGUI/Selection/Bring To Front &#=", true)]
static public bool BringForward2Validation () { return (Selection.activeGameObject != null); }
[MenuItem("NGUI/Selection/Push To Back &#-", false, 0)]
static public void PushBack2 ()
{
int val = 0;
for (int i = 0; i < Selection.gameObjects.Length; ++i)
val |= NGUITools.AdjustDepth(Selection.gameObjects[i], -1000);
if ((val & 1) != 0)
{
NGUITools.NormalizePanelDepths();
if (UIPanelTool.instance != null)
UIPanelTool.instance.Repaint();
}
if ((val & 2) != 0) NGUITools.NormalizeWidgetDepths();
}
[MenuItem("NGUI/Selection/Push To Back &#-", true)]
static public bool PushBack2Validation () { return (Selection.activeGameObject != null); }
[MenuItem("NGUI/Selection/Adjust Depth By +1 %=", false, 0)]
static public void BringForward ()
{
int val = 0;
for (int i = 0; i < Selection.gameObjects.Length; ++i)
val |= NGUITools.AdjustDepth(Selection.gameObjects[i], 1);
if (((val & 1) != 0) && UIPanelTool.instance != null)
UIPanelTool.instance.Repaint();
}
[MenuItem("NGUI/Selection/Adjust Depth By +1 %=", true)]
static public bool BringForwardValidation () { return (Selection.activeGameObject != null); }
[MenuItem("NGUI/Selection/Adjust Depth By -1 %-", false, 0)]
static public void PushBack ()
{
int val = 0;
for (int i = 0; i < Selection.gameObjects.Length; ++i)
val |= NGUITools.AdjustDepth(Selection.gameObjects[i], -1);
if (((val & 1) != 0) && UIPanelTool.instance != null)
UIPanelTool.instance.Repaint();
}
[MenuItem("NGUI/Selection/Adjust Depth By -1 %-", true)]
static public bool PushBackValidation () { return (Selection.activeGameObject != null); }
[MenuItem("NGUI/Selection/Make Pixel Perfect &#p", false, 0)]
static void PixelPerfectSelection ()
{
foreach (Transform t in Selection.transforms)
NGUITools.MakePixelPerfect(t);
}
[MenuItem("NGUI/Selection/Make Pixel Perfect &#p", true)]
static bool PixelPerfectSelectionValidation ()
{
return (Selection.activeTransform != null);
}
#endregion
#region Create
[MenuItem("NGUI/Create/Sprite &#s", false, 6)]
static public void AddSprite ()
{
GameObject go = NGUIEditorTools.SelectedRoot(true);
if (go != null)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Add a Sprite");
#endif
Selection.activeGameObject = NGUISettings.AddSprite(go).gameObject;
}
else
{
Debug.Log("You must select a game object first.");
}
}
[MenuItem("NGUI/Create/Label &#l", false, 6)]
static public void AddLabel ()
{
GameObject go = NGUIEditorTools.SelectedRoot(true);
if (go != null)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Add a Label");
#endif
Selection.activeGameObject = NGUISettings.AddLabel(go).gameObject;
}
else
{
Debug.Log("You must select a game object first.");
}
}
[MenuItem("NGUI/Create/Texture &#t", false, 6)]
static public void AddTexture ()
{
GameObject go = NGUIEditorTools.SelectedRoot(true);
if (go != null)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Add a Texture");
#endif
Selection.activeGameObject = NGUISettings.AddTexture(go).gameObject;
}
else
{
Debug.Log("You must select a game object first.");
}
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
[MenuItem("NGUI/Create/Unity 2D Sprite &#r", false, 6)]
static public void AddSprite2D ()
{
GameObject go = NGUIEditorTools.SelectedRoot(true);
if (go != null) Selection.activeGameObject = NGUISettings.Add2DSprite(go).gameObject;
else Debug.Log("You must select a game object first.");
}
#endif
[MenuItem("NGUI/Create/Widget &#w", false, 6)]
static public void AddWidget ()
{
GameObject go = NGUIEditorTools.SelectedRoot(true);
if (go != null)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Add a Widget");
#endif
Selection.activeGameObject = NGUISettings.AddWidget(go).gameObject;
}
else
{
Debug.Log("You must select a game object first.");
}
}
[MenuItem("NGUI/Create/", false, 6)]
static void AddBreaker123 () {}
[MenuItem("NGUI/Create/Anchor (Legacy)", false, 6)]
static void AddAnchor2 () { Add<UIAnchor>(); }
[MenuItem("NGUI/Create/Panel", false, 6)]
static void AddPanel ()
{
UIPanel panel = NGUISettings.AddPanel(SelectedRoot());
Selection.activeGameObject = (panel == null) ? NGUIEditorTools.SelectedRoot(true) : panel.gameObject;
}
[MenuItem("NGUI/Create/Scroll View", false, 6)]
static void AddScrollView ()
{
UIPanel panel = NGUISettings.AddPanel(SelectedRoot());
if (panel == null) panel = NGUIEditorTools.SelectedRoot(true).GetComponent<UIPanel>();
panel.clipping = UIDrawCall.Clipping.SoftClip;
panel.name = "Scroll View";
panel.gameObject.AddComponent<UIScrollView>();
Selection.activeGameObject = panel.gameObject;
}
[MenuItem("NGUI/Create/Grid", false, 6)]
static void AddGrid () { Add<UIGrid>(); }
[MenuItem("NGUI/Create/Table", false, 6)]
static void AddTable () { Add<UITable>(); }
static T Add<T> () where T : MonoBehaviour
{
T t = NGUITools.AddChild<T>(SelectedRoot());
Selection.activeGameObject = t.gameObject;
return t;
}
[MenuItem("NGUI/Create/2D UI", false, 6)]
[MenuItem("Assets/NGUI/Create 2D UI", false, 1)]
static void Create2D () { UICreateNewUIWizard.CreateNewUI(UICreateNewUIWizard.CameraType.Simple2D); }
[MenuItem("NGUI/Create/2D UI", true)]
[MenuItem("Assets/NGUI/Create 2D UI", true, 1)]
static bool Create2Da () { return UIRoot.list.Count == 0 || UICamera.list.size == 0 || !UICamera.list[0].camera.isOrthoGraphic; }
[MenuItem("NGUI/Create/3D UI", false, 6)]
[MenuItem("Assets/NGUI/Create 3D UI", false, 1)]
static void Create3D () { UICreateNewUIWizard.CreateNewUI(UICreateNewUIWizard.CameraType.Advanced3D); }
[MenuItem("NGUI/Create/3D UI", true)]
[MenuItem("Assets/NGUI/Create 3D UI", true, 1)]
static bool Create3Da () { return UIRoot.list.Count == 0 || UICamera.list.size == 0 || UICamera.list[0].camera.isOrthoGraphic; }
#endregion
#region Attach
static void AddIfMissing<T> () where T : Component
{
if (Selection.activeGameObject != null)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
Selection.gameObjects[i].AddMissingComponent<T>();
}
else Debug.Log("You must select a game object first.");
}
static bool Exists<T> () where T : Component
{
GameObject go = Selection.activeGameObject;
if (go != null) return go.GetComponent<T>() != null;
return false;
}
[MenuItem("NGUI/Attach/Collider &#c", false, 7)]
static public void AddCollider ()
{
if (Selection.activeGameObject != null)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AddWidgetCollider(Selection.gameObjects[i]);
}
else Debug.Log("You must select a game object first, such as your button.");
}
//[MenuItem("NGUI/Attach/Anchor", false, 7)]
//static public void Add1 () { AddIfMissing<UIAnchor>(); }
//[MenuItem("NGUI/Attach/Anchor", true)]
//static public bool Add1a () { return !Exists<UIAnchor>(); }
//[MenuItem("NGUI/Attach/Stretch (Legacy)", false, 7)]
//static public void Add2 () { AddIfMissing<UIStretch>(); }
//[MenuItem("NGUI/Attach/Stretch (Legacy)", true)]
//static public bool Add2a () { return !Exists<UIStretch>(); }
//[MenuItem("NGUI/Attach/", false, 7)]
//static public void Add3s () {}
[MenuItem("NGUI/Attach/Button Script", false, 7)]
static public void Add3 () { AddIfMissing<UIButton>(); }
[MenuItem("NGUI/Attach/Toggle Script", false, 7)]
static public void Add4 () { AddIfMissing<UIToggle>(); }
[MenuItem("NGUI/Attach/Slider Script", false, 7)]
static public void Add5 () { AddIfMissing<UISlider>(); }
[MenuItem("NGUI/Attach/Scroll Bar Script", false, 7)]
static public void Add6 () { AddIfMissing<UIScrollBar>(); }
[MenuItem("NGUI/Attach/Progress Bar Script", false, 7)]
static public void Add7 () { AddIfMissing<UIProgressBar>(); }
[MenuItem("NGUI/Attach/Popup List Script", false, 7)]
static public void Add8 () { AddIfMissing<UIPopupList>(); }
[MenuItem("NGUI/Attach/Input Field Script", false, 7)]
static public void Add9 () { AddIfMissing<UIInput>(); }
[MenuItem("NGUI/Attach/Key Binding Script", false, 7)]
static public void Add10 () { AddIfMissing<UIKeyBinding>(); }
[MenuItem("NGUI/Attach/Key Navigation Script", false, 7)]
static public void Add10a () { AddIfMissing<UIKeyNavigation>(); }
[MenuItem("NGUI/Attach/Play Tween Script", false, 7)]
static public void Add11 () { AddIfMissing<UIPlayTween>(); }
[MenuItem("NGUI/Attach/Play Animation Script", false, 7)]
static public void Add12 () { AddIfMissing<UIPlayAnimation>(); }
[MenuItem("NGUI/Attach/Play Sound Script", false, 7)]
static public void Add13 () { AddIfMissing<UIPlaySound>(); }
[MenuItem("NGUI/Attach/Localization Script", false, 7)]
static public void Add14 () { AddIfMissing<UILocalize>(); }
#endregion
#region Tweens
[MenuItem("NGUI/Tween/Alpha", false, 8)]
static void Tween1 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenAlpha>(); }
[MenuItem("NGUI/Tween/Alpha", true)]
static bool Tween1a () { return (Selection.activeGameObject != null) && (Selection.activeGameObject.GetComponent<UIWidget>() != null); }
[MenuItem("NGUI/Tween/Color", false, 8)]
static void Tween2 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenColor>(); }
[MenuItem("NGUI/Tween/Color", true)]
static bool Tween2a () { return (Selection.activeGameObject != null) && (Selection.activeGameObject.GetComponent<UIWidget>() != null); }
[MenuItem("NGUI/Tween/Width", false, 8)]
static void Tween3 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenWidth>(); }
[MenuItem("NGUI/Tween/Width", true)]
static bool Tween3a () { return (Selection.activeGameObject != null) && (Selection.activeGameObject.GetComponent<UIWidget>() != null); }
[MenuItem("NGUI/Tween/Height", false, 8)]
static void Tween4 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenHeight>(); }
[MenuItem("NGUI/Tween/Height", true)]
static bool Tween4a () { return (Selection.activeGameObject != null) && (Selection.activeGameObject.GetComponent<UIWidget>() != null); }
[MenuItem("NGUI/Tween/Position", false, 8)]
static void Tween5 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenPosition>(); }
[MenuItem("NGUI/Tween/Position", true)]
static bool Tween5a () { return (Selection.activeGameObject != null); }
[MenuItem("NGUI/Tween/Rotation", false, 8)]
static void Tween6 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenRotation>(); }
[MenuItem("NGUI/Tween/Rotation", true)]
static bool Tween6a () { return (Selection.activeGameObject != null); }
[MenuItem("NGUI/Tween/Scale", false, 8)]
static void Tween7 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenScale>(); }
[MenuItem("NGUI/Tween/Scale", true)]
static bool Tween7a () { return (Selection.activeGameObject != null); }
[MenuItem("NGUI/Tween/Transform", false, 8)]
static void Tween8 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenTransform>(); }
[MenuItem("NGUI/Tween/Transform", true)]
static bool Tween8a () { return (Selection.activeGameObject != null); }
[MenuItem("NGUI/Tween/Volume", false, 8)]
static void Tween9 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenVolume>(); }
[MenuItem("NGUI/Tween/Volume", true)]
static bool Tween9a () { return (Selection.activeGameObject != null) && (Selection.activeGameObject.GetComponent<AudioSource>() != null); }
[MenuItem("NGUI/Tween/Field of View", false, 8)]
static void Tween10 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenFOV>(); }
[MenuItem("NGUI/Tween/Field of View", true)]
static bool Tween10a () { return (Selection.activeGameObject != null) && (Selection.activeGameObject.GetComponent<Camera>() != null); }
[MenuItem("NGUI/Tween/Orthographic Size", false, 8)]
static void Tween11 () { if (Selection.activeGameObject != null) Selection.activeGameObject.AddMissingComponent<TweenOrthoSize>(); }
[MenuItem("NGUI/Tween/Orthographic Size", true)]
static bool Tween11a () { return (Selection.activeGameObject != null) && (Selection.activeGameObject.GetComponent<Camera>() != null); }
#endregion
#region Open
[MenuItem("NGUI/Open/Atlas Maker", false, 9)]
[MenuItem("Assets/NGUI/Open Atlas Maker", false, 0)]
static public void OpenAtlasMaker ()
{
EditorWindow.GetWindow<UIAtlasMaker>(false, "Atlas Maker", true).Show();
}
[MenuItem("NGUI/Open/Font Maker", false, 9)]
[MenuItem("Assets/NGUI/Open Bitmap Font Maker", false, 0)]
static public void OpenFontMaker ()
{
EditorWindow.GetWindow<UIFontMaker>(false, "Font Maker", true).Show();
}
[MenuItem("NGUI/Open/", false, 9)]
[MenuItem("Assets/NGUI/", false, 0)]
static public void OpenSeparator2 () { }
[MenuItem("NGUI/Open/Panel Tool", false, 9)]
static public void OpenPanelWizard ()
{
EditorWindow.GetWindow<UIPanelTool>(false, "Panel Tool", true).Show();
}
[MenuItem("NGUI/Open/Draw Call Tool", false, 9)]
static public void OpenDCTool ()
{
EditorWindow.GetWindow<UIDrawCallViewer>(false, "Draw Call Tool", true).Show();
}
[MenuItem("NGUI/Open/Camera Tool", false, 9)]
static public void OpenCameraWizard ()
{
EditorWindow.GetWindow<UICameraTool>(false, "Camera Tool", true).Show();
}
[MenuItem("NGUI/Open/Widget Wizard (Legacy)", false, 9)]
static public void CreateWidgetWizard ()
{
EditorWindow.GetWindow<UICreateWidgetWizard>(false, "Widget Tool", true).Show();
}
//[MenuItem("NGUI/Open/UI Wizard (Legacy)", false, 9)]
//static public void CreateUIWizard ()
//{
// EditorWindow.GetWindow<UICreateNewUIWizard>(false, "UI Tool", true).Show();
//}
#endregion
#region Options
[MenuItem("NGUI/Options/Handles/Turn On", false, 10)]
static public void TurnHandlesOn () { UIWidget.showHandlesWithMoveTool = true; }
[MenuItem("NGUI/Options/Handles/Turn On", true, 10)]
static public bool TurnHandlesOnCheck () { return !UIWidget.showHandlesWithMoveTool; }
[MenuItem("NGUI/Options/Handles/Turn Off", false, 10)]
static public void TurnHandlesOff () { UIWidget.showHandlesWithMoveTool = false; }
[MenuItem("NGUI/Options/Handles/Turn Off", true, 10)]
static public bool TurnHandlesOffCheck () { return UIWidget.showHandlesWithMoveTool; }
[MenuItem("NGUI/Options/Handles/Set to Blue", false, 10)]
static public void SetToBlue () { NGUISettings.colorMode = NGUISettings.ColorMode.Blue; }
[MenuItem("NGUI/Options/Handles/Set to Blue", true, 10)]
static public bool SetToBlueCheck () { return UIWidget.showHandlesWithMoveTool && NGUISettings.colorMode != NGUISettings.ColorMode.Blue; }
[MenuItem("NGUI/Options/Handles/Set to Orange", false, 10)]
static public void SetToOrange () { NGUISettings.colorMode = NGUISettings.ColorMode.Orange; }
[MenuItem("NGUI/Options/Handles/Set to Orange", true, 10)]
static public bool SetToOrangeCheck () { return UIWidget.showHandlesWithMoveTool && NGUISettings.colorMode != NGUISettings.ColorMode.Orange; }
[MenuItem("NGUI/Options/Handles/Set to Green", false, 10)]
static public void SetToGreen () { NGUISettings.colorMode = NGUISettings.ColorMode.Green; }
[MenuItem("NGUI/Options/Handles/Set to Green", true, 10)]
static public bool SetToGreenCheck () { return UIWidget.showHandlesWithMoveTool && NGUISettings.colorMode != NGUISettings.ColorMode.Green; }
[MenuItem("NGUI/Options/Snapping/Turn On", false, 10)]
static public void TurnSnapOn () { NGUISnap.allow = true; }
[MenuItem("NGUI/Options/Snapping/Turn On", true, 10)]
static public bool TurnSnapOnCheck () { return !NGUISnap.allow; }
[MenuItem("NGUI/Options/Snapping/Turn Off", false, 10)]
static public void TurnSnapOff () { NGUISnap.allow = false; }
[MenuItem("NGUI/Options/Snapping/Turn Off", true, 10)]
static public bool TurnSnapOffCheck () { return NGUISnap.allow; }
[MenuItem("NGUI/Options/Guides/Always On", false, 10)]
static public void TurnGuidesOn () { NGUISettings.drawGuides = true; }
[MenuItem("NGUI/Options/Guides/Always On", true, 10)]
static public bool TurnGuidesOnCheck () { return !NGUISettings.drawGuides; }
[MenuItem("NGUI/Options/Guides/Only When Needed", false, 10)]
static public void TurnGuidesOff () { NGUISettings.drawGuides = false; }
[MenuItem("NGUI/Options/Guides/Only When Needed", true, 10)]
static public bool TurnGuidesOffCheck () { return NGUISettings.drawGuides; }
#endregion
[MenuItem("NGUI/Normalize Depth Hierarchy �", false, 11)]
static public void Normalize () { NGUITools.NormalizeDepths(); }
[MenuItem("NGUI/", false, 11)]
static void Breaker () { }
[MenuItem("NGUI/Help", false, 12)]
static public void Help () { NGUIHelp.Show(); }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUIMenu.cs
|
C#
|
asf20
| 18,007
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_FLASH
#define DYNAMIC_FONT
#endif
using UnityEngine;
using UnityEditor;
/// <summary>
/// Inspector class used to edit UILabels.
/// </summary>
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UILabel))]
#else
[CustomEditor(typeof(UILabel), true)]
#endif
public class UILabelInspector : UIWidgetInspector
{
public enum FontType
{
NGUI,
Unity,
}
UILabel mLabel;
FontType mFontType;
protected override void OnEnable ()
{
base.OnEnable();
SerializedProperty bit = serializedObject.FindProperty("mFont");
mFontType = (bit != null && bit.objectReferenceValue != null) ? FontType.NGUI : FontType.Unity;
}
void OnNGUIFont (Object obj)
{
serializedObject.Update();
SerializedProperty sp = serializedObject.FindProperty("mFont");
sp.objectReferenceValue = obj;
serializedObject.ApplyModifiedProperties();
NGUISettings.ambigiousFont = obj;
}
void OnUnityFont (Object obj)
{
serializedObject.Update();
SerializedProperty sp = serializedObject.FindProperty("mTrueTypeFont");
sp.objectReferenceValue = obj;
serializedObject.ApplyModifiedProperties();
NGUISettings.ambigiousFont = obj;
}
/// <summary>
/// Draw the label's properties.
/// </summary>
protected override bool ShouldDrawProperties ()
{
mLabel = mWidget as UILabel;
GUILayout.BeginHorizontal();
#if DYNAMIC_FONT
mFontType = (FontType)EditorGUILayout.EnumPopup(mFontType, "DropDown", GUILayout.Width(74f));
if (NGUIEditorTools.DrawPrefixButton("Font", GUILayout.Width(64f)))
#else
mFontType = FontType.NGUI;
if (NGUIEditorTools.DrawPrefixButton("Font", GUILayout.Width(74f)))
#endif
{
if (mFontType == FontType.NGUI)
{
ComponentSelector.Show<UIFont>(OnNGUIFont);
}
else
{
ComponentSelector.Show<Font>(OnUnityFont, new string[] { ".ttf", ".otf" });
}
}
bool isValid = false;
SerializedProperty fnt = null;
SerializedProperty ttf = null;
if (mFontType == FontType.NGUI)
{
fnt = NGUIEditorTools.DrawProperty("", serializedObject, "mFont", GUILayout.MinWidth(40f));
if (fnt.objectReferenceValue != null)
{
NGUISettings.ambigiousFont = fnt.objectReferenceValue;
isValid = true;
}
}
else
{
ttf = NGUIEditorTools.DrawProperty("", serializedObject, "mTrueTypeFont", GUILayout.MinWidth(40f));
if (ttf.objectReferenceValue != null)
{
NGUISettings.ambigiousFont = ttf.objectReferenceValue;
isValid = true;
}
}
GUILayout.EndHorizontal();
EditorGUI.BeginDisabledGroup(!isValid);
{
UIFont uiFont = (fnt != null) ? fnt.objectReferenceValue as UIFont : null;
Font dynFont = (ttf != null) ? ttf.objectReferenceValue as Font : null;
if (uiFont != null && uiFont.isDynamic)
{
dynFont = uiFont.dynamicFont;
uiFont = null;
}
if (dynFont != null)
{
GUILayout.BeginHorizontal();
{
EditorGUI.BeginDisabledGroup((ttf != null) ? ttf.hasMultipleDifferentValues : fnt.hasMultipleDifferentValues);
SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));
NGUISettings.fontSize = prop.intValue;
prop = NGUIEditorTools.DrawProperty("", serializedObject, "mFontStyle", GUILayout.MinWidth(40f));
NGUISettings.fontStyle = (FontStyle)prop.intValue;
GUILayout.Space(18f);
EditorGUI.EndDisabledGroup();
}
GUILayout.EndHorizontal();
NGUIEditorTools.DrawProperty("Material", serializedObject, "mMaterial");
}
else if (uiFont != null)
{
GUILayout.BeginHorizontal();
SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));
EditorGUI.BeginDisabledGroup(true);
if (!serializedObject.isEditingMultipleObjects)
GUILayout.Label(" Default: " + mLabel.defaultFontSize);
EditorGUI.EndDisabledGroup();
NGUISettings.fontSize = prop.intValue;
GUILayout.EndHorizontal();
}
bool ww = GUI.skin.textField.wordWrap;
GUI.skin.textField.wordWrap = true;
SerializedProperty sp = serializedObject.FindProperty("mText");
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
GUI.changed = false;
string text = EditorGUILayout.TextArea(sp.stringValue, GUI.skin.textArea, GUILayout.Height(100f));
if (GUI.changed) sp.stringValue = text;
#else
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
GUILayout.Space(-16f);
#endif
if (sp.hasMultipleDifferentValues)
{
NGUIEditorTools.DrawProperty("", sp, GUILayout.Height(128f));
}
else
{
GUIStyle style = new GUIStyle(EditorStyles.textField);
style.wordWrap = true;
float height = style.CalcHeight(new GUIContent(sp.stringValue), Screen.width - 100f);
bool offset = true;
if (height > 90f)
{
offset = false;
height = style.CalcHeight(new GUIContent(sp.stringValue), Screen.width - 20f);
}
else
{
GUILayout.BeginHorizontal();
GUILayout.BeginVertical(GUILayout.Width(76f));
GUILayout.Space(3f);
GUILayout.Label("Text");
GUILayout.EndVertical();
GUILayout.BeginVertical();
}
Rect rect = EditorGUILayout.GetControlRect(GUILayout.Height(height));
GUI.changed = false;
string text = EditorGUI.TextArea(rect, sp.stringValue, style);
if (GUI.changed) sp.stringValue = text;
if (offset)
{
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
}
#endif
GUI.skin.textField.wordWrap = ww;
SerializedProperty ov = NGUIEditorTools.DrawPaddedProperty("Overflow", serializedObject, "mOverflow");
NGUISettings.overflowStyle = (UILabel.Overflow)ov.intValue;
NGUIEditorTools.DrawPaddedProperty("Alignment", serializedObject, "mAlignment");
if (dynFont != null)
NGUIEditorTools.DrawPaddedProperty("Keep crisp", serializedObject, "keepCrispWhenShrunk");
EditorGUI.BeginDisabledGroup(mLabel.bitmapFont != null && mLabel.bitmapFont.packedFontShader);
GUILayout.BeginHorizontal();
SerializedProperty gr = NGUIEditorTools.DrawProperty("Gradient", serializedObject, "mApplyGradient",
#if UNITY_3_5
GUILayout.Width(93f));
#else
GUILayout.Width(95f));
#endif
EditorGUI.BeginDisabledGroup(!gr.hasMultipleDifferentValues && !gr.boolValue);
{
NGUIEditorTools.SetLabelWidth(30f);
NGUIEditorTools.DrawProperty("Top", serializedObject, "mGradientTop", GUILayout.MinWidth(40f));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
NGUIEditorTools.SetLabelWidth(50f);
#if UNITY_3_5
GUILayout.Space(81f);
#else
GUILayout.Space(79f);
#endif
NGUIEditorTools.DrawProperty("Bottom", serializedObject, "mGradientBottom", GUILayout.MinWidth(40f));
NGUIEditorTools.SetLabelWidth(80f);
}
EditorGUI.EndDisabledGroup();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Effect", GUILayout.Width(76f));
sp = NGUIEditorTools.DrawProperty("", serializedObject, "mEffectStyle", GUILayout.MinWidth(16f));
EditorGUI.BeginDisabledGroup(!sp.hasMultipleDifferentValues && !sp.boolValue);
{
NGUIEditorTools.DrawProperty("", serializedObject, "mEffectColor", GUILayout.MinWidth(10f));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
GUILayout.Label(" ", GUILayout.Width(56f));
NGUIEditorTools.SetLabelWidth(20f);
NGUIEditorTools.DrawProperty("X", serializedObject, "mEffectDistance.x", GUILayout.MinWidth(40f));
NGUIEditorTools.DrawProperty("Y", serializedObject, "mEffectDistance.y", GUILayout.MinWidth(40f));
GUILayout.Space(18f);
NGUIEditorTools.SetLabelWidth(80f);
}
}
EditorGUI.EndDisabledGroup();
GUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
GUILayout.BeginHorizontal();
GUILayout.Label("Spacing", GUILayout.Width(56f));
NGUIEditorTools.SetLabelWidth(20f);
NGUIEditorTools.DrawProperty("X", serializedObject, "mSpacingX", GUILayout.MinWidth(40f));
NGUIEditorTools.DrawProperty("Y", serializedObject, "mSpacingY", GUILayout.MinWidth(40f));
GUILayout.Space(18f);
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.EndHorizontal();
NGUIEditorTools.DrawProperty("Max Lines", serializedObject, "mMaxLineCount", GUILayout.Width(110f));
GUILayout.BeginHorizontal();
sp = NGUIEditorTools.DrawProperty("BBCode", serializedObject, "mEncoding", GUILayout.Width(100f));
EditorGUI.BeginDisabledGroup(!sp.boolValue || mLabel.bitmapFont == null || !mLabel.bitmapFont.hasSymbols);
NGUIEditorTools.SetLabelWidth(60f);
NGUIEditorTools.DrawPaddedProperty("Symbols", serializedObject, "mSymbols");
NGUIEditorTools.SetLabelWidth(80f);
EditorGUI.EndDisabledGroup();
GUILayout.EndHorizontal();
}
EditorGUI.EndDisabledGroup();
return isValid;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UILabelInspector.cs
|
C#
|
asf20
| 8,912
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Draw Call Viewer shows a list of draw calls created by NGUI and lets you hide them selectively.
/// </summary>
public class UIDrawCallViewer : EditorWindow
{
static public UIDrawCallViewer instance;
enum Visibility
{
Visible,
Hidden,
}
enum ShowFilter
{
AllPanels,
SelectedPanel,
}
Vector2 mScroll = Vector2.zero;
void OnEnable () { instance = this; }
void OnDisable () { instance = null; }
void OnSelectionChange () { Repaint(); }
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
BetterList<UIDrawCall> dcs = UIDrawCall.activeList;
dcs.Sort(delegate(UIDrawCall a, UIDrawCall b)
{
return a.finalRenderQueue.CompareTo(b.finalRenderQueue);
});
if (dcs.size == 0)
{
EditorGUILayout.HelpBox("No NGUI draw calls present in the scene", MessageType.Info);
return;
}
UIPanel selectedPanel = NGUITools.FindInParents<UIPanel>(Selection.activeGameObject);
GUILayout.Space(12f);
NGUIEditorTools.SetLabelWidth(100f);
ShowFilter show = (NGUISettings.showAllDCs ? ShowFilter.AllPanels : ShowFilter.SelectedPanel);
if ((ShowFilter)EditorGUILayout.EnumPopup("Draw Call Filter", show) != show)
NGUISettings.showAllDCs = !NGUISettings.showAllDCs;
GUILayout.Space(6f);
if (selectedPanel == null && !NGUISettings.showAllDCs)
{
EditorGUILayout.HelpBox("No panel selected", MessageType.Info);
return;
}
NGUIEditorTools.SetLabelWidth(80f);
mScroll = GUILayout.BeginScrollView(mScroll);
int dcCount = 0;
for (int i = 0; i < dcs.size; ++i)
{
UIDrawCall dc = dcs[i];
string key = "Draw Call " + (i + 1);
bool highlight = (selectedPanel == null || selectedPanel == dc.manager);
if (!highlight)
{
if (!NGUISettings.showAllDCs) continue;
if (UnityEditor.EditorPrefs.GetBool(key, true))
{
GUI.color = new Color(0.85f, 0.85f, 0.85f);
}
else
{
GUI.contentColor = new Color(0.85f, 0.85f, 0.85f);
}
}
else GUI.contentColor = Color.white;
++dcCount;
string name = key + " of " + dcs.size;
if (!dc.isActive) name = name + " (HIDDEN)";
else if (!highlight) name = name + " (" + dc.manager.name + ")";
if (NGUIEditorTools.DrawHeader(name, key))
{
GUI.color = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f);
NGUIEditorTools.BeginContents();
EditorGUILayout.ObjectField("Material", dc.dynamicMaterial, typeof(Material), false);
int count = 0;
for (int a = 0; a < UIPanel.list.size; ++a)
{
UIPanel p = UIPanel.list.buffer[a];
for (int b = 0; b < p.widgets.size; ++b)
{
UIWidget w = p.widgets.buffer[b];
if (w.drawCall == dc) ++count;
}
}
string myPath = NGUITools.GetHierarchy(dc.manager.cachedGameObject);
string remove = myPath + "\\";
string[] list = new string[count + 1];
list[0] = count.ToString();
count = 0;
for (int a = 0; a < UIPanel.list.size; ++a)
{
UIPanel p = UIPanel.list.buffer[a];
for (int b = 0; b < p.widgets.size; ++b)
{
UIWidget w = p.widgets.buffer[b];
if (w.drawCall == dc)
{
string path = NGUITools.GetHierarchy(w.cachedGameObject);
list[++count] = count + ". " + (string.Equals(path, myPath) ? w.name : path.Replace(remove, ""));
}
}
}
GUILayout.BeginHorizontal();
int sel = EditorGUILayout.Popup("Widgets", 0, list);
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (sel != 0)
{
count = 0;
for (int a = 0; a < UIPanel.list.size; ++a)
{
UIPanel p = UIPanel.list.buffer[a];
for (int b = 0; b < p.widgets.size; ++b)
{
UIWidget w = p.widgets.buffer[b];
if (w.drawCall == dc && ++count == sel)
{
Selection.activeGameObject = w.gameObject;
break;
}
}
}
}
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Render Q", dc.finalRenderQueue.ToString(), GUILayout.Width(120f));
bool draw = (Visibility)EditorGUILayout.EnumPopup(dc.isActive ? Visibility.Visible : Visibility.Hidden) == Visibility.Visible;
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (dc.isActive != draw)
{
dc.isActive = draw;
NGUITools.SetDirty(dc.manager);
}
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Triangles", dc.triangles.ToString(), GUILayout.Width(120f));
if (dc.manager != selectedPanel)
{
if (GUILayout.Button("Select the Panel"))
{
Selection.activeGameObject = dc.manager.gameObject;
}
GUILayout.Space(18f);
}
GUILayout.EndHorizontal();
if (dc.manager.clipping != UIDrawCall.Clipping.None && !dc.isClipped)
{
EditorGUILayout.HelpBox("You must switch this material's shader to Unlit/Transparent Colored or Unlit/Premultiplied Colored in order for clipping to work.",
MessageType.Warning);
}
NGUIEditorTools.EndContents();
GUI.color = Color.white;
}
}
if (dcCount == 0)
{
EditorGUILayout.HelpBox("No draw calls found", MessageType.Info);
}
GUILayout.EndScrollView();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIDrawCallViewer.cs
|
C#
|
asf20
| 5,370
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UIForwardEvents))]
public class UIForwardEventsEditor : Editor
{
public override void OnInspectorGUI ()
{
EditorGUILayout.HelpBox("This is a legacy component. Consider using the Event Trigger instead.", MessageType.Warning);
base.OnInspectorGUI();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIForwardEventsEditor.cs
|
C#
|
asf20
| 528
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if UNITY_3_5
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UITable))]
public class UITableEditor : UIWidgetContainerEditor
{
}
#endif
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UITableEditor.cs
|
C#
|
asf20
| 358
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
// Dynamic font support contributed by the NGUI community members:
// Unisip, zh4ox, Mudwiz, Nicki, DarkMagicCK.
#if !UNITY_3_5 && !UNITY_FLASH
#define DYNAMIC_FONT
#endif
using UnityEngine;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// UIFont contains everything needed to be able to print text.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/NGUI Font")]
public class UIFont : MonoBehaviour
{
[HideInInspector][SerializeField] Material mMat;
[HideInInspector][SerializeField] Rect mUVRect = new Rect(0f, 0f, 1f, 1f);
[HideInInspector][SerializeField] BMFont mFont = new BMFont();
[HideInInspector][SerializeField] UIAtlas mAtlas;
[HideInInspector][SerializeField] UIFont mReplacement;
// List of symbols, such as emoticons like ":)", ":(", etc
[HideInInspector][SerializeField] List<BMSymbol> mSymbols = new List<BMSymbol>();
// Used for dynamic fonts
[HideInInspector][SerializeField] Font mDynamicFont;
[HideInInspector][SerializeField] int mDynamicFontSize = 16;
[HideInInspector][SerializeField] FontStyle mDynamicFontStyle = FontStyle.Normal;
// Cached value
[System.NonSerialized]
UISpriteData mSprite = null;
int mPMA = -1;
int mPacked = -1;
/// <summary>
/// Access to the BMFont class directly.
/// </summary>
public BMFont bmFont
{
get
{
return (mReplacement != null) ? mReplacement.bmFont : mFont;
}
set
{
if (mReplacement != null) mReplacement.bmFont = value;
else mFont = value;
}
}
/// <summary>
/// Original width of the font's texture in pixels.
/// </summary>
public int texWidth
{
get
{
return (mReplacement != null) ? mReplacement.texWidth : ((mFont != null) ? mFont.texWidth : 1);
}
set
{
if (mReplacement != null) mReplacement.texWidth = value;
else if (mFont != null) mFont.texWidth = value;
}
}
/// <summary>
/// Original height of the font's texture in pixels.
/// </summary>
public int texHeight
{
get
{
return (mReplacement != null) ? mReplacement.texHeight : ((mFont != null) ? mFont.texHeight : 1);
}
set
{
if (mReplacement != null) mReplacement.texHeight = value;
else if (mFont != null) mFont.texHeight = value;
}
}
/// <summary>
/// Whether the font has any symbols defined.
/// </summary>
public bool hasSymbols { get { return (mReplacement != null) ? mReplacement.hasSymbols : (mSymbols != null && mSymbols.Count != 0); } }
/// <summary>
/// List of symbols within the font.
/// </summary>
public List<BMSymbol> symbols { get { return (mReplacement != null) ? mReplacement.symbols : mSymbols; } }
/// <summary>
/// Atlas used by the font, if any.
/// </summary>
public UIAtlas atlas
{
get
{
return (mReplacement != null) ? mReplacement.atlas : mAtlas;
}
set
{
if (mReplacement != null)
{
mReplacement.atlas = value;
}
else if (mAtlas != value)
{
if (value == null)
{
if (mAtlas != null) mMat = mAtlas.spriteMaterial;
if (sprite != null) mUVRect = uvRect;
}
mPMA = -1;
mAtlas = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Get or set the material used by this font.
/// </summary>
public Material material
{
get
{
if (mReplacement != null) return mReplacement.material;
if (mAtlas != null) return mAtlas.spriteMaterial;
if (mMat != null)
{
if (mDynamicFont != null && mMat != mDynamicFont.material)
{
mMat.mainTexture = mDynamicFont.material.mainTexture;
}
return mMat;
}
if (mDynamicFont != null)
{
return mDynamicFont.material;
}
return null;
}
set
{
if (mReplacement != null)
{
mReplacement.material = value;
}
else if (mMat != value)
{
mPMA = -1;
mMat = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Whether the font is using a premultiplied alpha material.
/// </summary>
public bool premultipliedAlphaShader
{
get
{
if (mReplacement != null) return mReplacement.premultipliedAlphaShader;
if (mAtlas != null) return mAtlas.premultipliedAlpha;
if (mPMA == -1)
{
Material mat = material;
mPMA = (mat != null && mat.shader != null && mat.shader.name.Contains("Premultiplied")) ? 1 : 0;
}
return (mPMA == 1);
}
}
/// <summary>
/// Whether the font is a packed font.
/// </summary>
public bool packedFontShader
{
get
{
if (mReplacement != null) return mReplacement.packedFontShader;
if (mAtlas != null) return false;
if (mPacked == -1)
{
Material mat = material;
mPacked = (mat != null && mat.shader != null && mat.shader.name.Contains("Packed")) ? 1 : 0;
}
return (mPacked == 1);
}
}
/// <summary>
/// Convenience function that returns the texture used by the font.
/// </summary>
public Texture2D texture
{
get
{
if (mReplacement != null) return mReplacement.texture;
Material mat = material;
return (mat != null) ? mat.mainTexture as Texture2D : null;
}
}
/// <summary>
/// Offset and scale applied to all UV coordinates.
/// </summary>
public Rect uvRect
{
get
{
if (mReplacement != null) return mReplacement.uvRect;
return (mAtlas != null && sprite != null) ? mUVRect : new Rect(0f, 0f, 1f, 1f);
}
set
{
if (mReplacement != null)
{
mReplacement.uvRect = value;
}
else if (sprite == null && mUVRect != value)
{
mUVRect = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite used by the font, if any.
/// </summary>
public string spriteName
{
get
{
return (mReplacement != null) ? mReplacement.spriteName : mFont.spriteName;
}
set
{
if (mReplacement != null)
{
mReplacement.spriteName = value;
}
else if (mFont.spriteName != value)
{
mFont.spriteName = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Whether this is a valid font.
/// </summary>
#if DYNAMIC_FONT
public bool isValid { get { return mDynamicFont != null || mFont.isValid; } }
#else
public bool isValid { get { return mFont.isValid; } }
#endif
[System.Obsolete("Use UIFont.defaultSize instead")]
public int size
{
get { return defaultSize; }
set { defaultSize = value; }
}
/// <summary>
/// Pixel-perfect size of this font.
/// </summary>
public int defaultSize
{
get
{
if (mReplacement != null) return mReplacement.defaultSize;
if (isDynamic || mFont == null) return mDynamicFontSize;
return mFont.charSize;
}
set
{
if (mReplacement != null) mReplacement.defaultSize = value;
else mDynamicFontSize = value;
}
}
/// <summary>
/// Retrieves the sprite used by the font, if any.
/// </summary>
public UISpriteData sprite
{
get
{
if (mReplacement != null) return mReplacement.sprite;
if (mSprite == null && mAtlas != null && !string.IsNullOrEmpty(mFont.spriteName))
{
mSprite = mAtlas.GetSprite(mFont.spriteName);
if (mSprite == null) mSprite = mAtlas.GetSprite(name);
if (mSprite == null) mFont.spriteName = null;
else UpdateUVRect();
for (int i = 0, imax = mSymbols.Count; i < imax; ++i)
symbols[i].MarkAsChanged();
}
return mSprite;
}
}
/// <summary>
/// Setting a replacement atlas value will cause everything using this font to use the replacement font instead.
/// Suggested use: set up all your widgets to use a dummy font that points to the real font. Switching that font to
/// another one (for example an eastern language one) is then a simple matter of setting this field on your dummy font.
/// </summary>
public UIFont replacement
{
get
{
return mReplacement;
}
set
{
UIFont rep = value;
if (rep == this) rep = null;
if (mReplacement != rep)
{
if (rep != null && rep.replacement == this) rep.replacement = null;
if (mReplacement != null) MarkAsChanged();
mReplacement = rep;
MarkAsChanged();
}
}
}
/// <summary>
/// Whether the font is dynamic.
/// </summary>
public bool isDynamic { get { return (mReplacement != null) ? mReplacement.isDynamic : (mDynamicFont != null); } }
/// <summary>
/// Get or set the dynamic font source.
/// </summary>
public Font dynamicFont
{
get
{
return (mReplacement != null) ? mReplacement.dynamicFont : mDynamicFont;
}
set
{
if (mReplacement != null)
{
mReplacement.dynamicFont = value;
}
else if (mDynamicFont != value)
{
if (mDynamicFont != null) material = null;
mDynamicFont = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Get or set the dynamic font's style.
/// </summary>
public FontStyle dynamicFontStyle
{
get
{
return (mReplacement != null) ? mReplacement.dynamicFontStyle : mDynamicFontStyle;
}
set
{
if (mReplacement != null)
{
mReplacement.dynamicFontStyle = value;
}
else if (mDynamicFontStyle != value)
{
mDynamicFontStyle = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Trim the glyphs, making sure they never go past the trimmed texture bounds.
/// </summary>
void Trim ()
{
Texture tex = mAtlas.texture;
if (tex != null && mSprite != null)
{
Rect full = NGUIMath.ConvertToPixels(mUVRect, texture.width, texture.height, true);
Rect trimmed = new Rect(mSprite.x, mSprite.y, mSprite.width, mSprite.height);
int xMin = Mathf.RoundToInt(trimmed.xMin - full.xMin);
int yMin = Mathf.RoundToInt(trimmed.yMin - full.yMin);
int xMax = Mathf.RoundToInt(trimmed.xMax - full.xMin);
int yMax = Mathf.RoundToInt(trimmed.yMax - full.yMin);
mFont.Trim(xMin, yMin, xMax, yMax);
}
}
/// <summary>
/// Helper function that determines whether the font uses the specified one, taking replacements into account.
/// </summary>
bool References (UIFont font)
{
if (font == null) return false;
if (font == this) return true;
return (mReplacement != null) ? mReplacement.References(font) : false;
}
/// <summary>
/// Helper function that determines whether the two atlases are related.
/// </summary>
static public bool CheckIfRelated (UIFont a, UIFont b)
{
if (a == null || b == null) return false;
#if DYNAMIC_FONT
if (a.isDynamic && b.isDynamic && a.dynamicFont.fontNames[0] == b.dynamicFont.fontNames[0]) return true;
#endif
return a == b || a.References(b) || b.References(a);
}
Texture dynamicTexture
{
get
{
if (mReplacement) return mReplacement.dynamicTexture;
if (isDynamic) return mDynamicFont.material.mainTexture;
return null;
}
}
/// <summary>
/// Refresh all labels that use this font.
/// </summary>
public void MarkAsChanged ()
{
#if UNITY_EDITOR
NGUITools.SetDirty(gameObject);
#endif
if (mReplacement != null) mReplacement.MarkAsChanged();
mSprite = null;
UILabel[] labels = NGUITools.FindActive<UILabel>();
for (int i = 0, imax = labels.Length; i < imax; ++i)
{
UILabel lbl = labels[i];
if (lbl.enabled && NGUITools.GetActive(lbl.gameObject) && CheckIfRelated(this, lbl.bitmapFont))
{
UIFont fnt = lbl.bitmapFont;
lbl.bitmapFont = null;
lbl.bitmapFont = fnt;
}
}
// Clear all symbols
for (int i = 0, imax = mSymbols.Count; i < imax; ++i)
symbols[i].MarkAsChanged();
}
/// <summary>
/// Forcefully update the font's sprite reference.
/// </summary>
public void UpdateUVRect ()
{
if (mAtlas == null) return;
Texture tex = mAtlas.texture;
if (tex != null)
{
mUVRect = new Rect(
mSprite.x - mSprite.paddingLeft,
mSprite.y - mSprite.paddingTop,
mSprite.width + mSprite.paddingLeft + mSprite.paddingRight,
mSprite.height + mSprite.paddingTop + mSprite.paddingBottom);
mUVRect = NGUIMath.ConvertToTexCoords(mUVRect, tex.width, tex.height);
#if UNITY_EDITOR
// The font should always use the original texture size
if (mFont != null)
{
float tw = (float)mFont.texWidth / tex.width;
float th = (float)mFont.texHeight / tex.height;
if (tw != mUVRect.width || th != mUVRect.height)
{
//Debug.LogWarning("Font sprite size doesn't match the expected font texture size.\n" +
// "Did you use the 'inner padding' setting on the Texture Packer? It must remain at '0'.", this);
mUVRect.width = tw;
mUVRect.height = th;
}
}
#endif
// Trimmed sprite? Trim the glyphs
if (mSprite.hasPadding) Trim();
}
}
/// <summary>
/// Retrieve the specified symbol, optionally creating it if it's missing.
/// </summary>
BMSymbol GetSymbol (string sequence, bool createIfMissing)
{
for (int i = 0, imax = mSymbols.Count; i < imax; ++i)
{
BMSymbol sym = mSymbols[i];
if (sym.sequence == sequence) return sym;
}
if (createIfMissing)
{
BMSymbol sym = new BMSymbol();
sym.sequence = sequence;
mSymbols.Add(sym);
return sym;
}
return null;
}
/// <summary>
/// Retrieve the symbol at the beginning of the specified sequence, if a match is found.
/// </summary>
public BMSymbol MatchSymbol (string text, int offset, int textLength)
{
// No symbols present
int count = mSymbols.Count;
if (count == 0) return null;
textLength -= offset;
// Run through all symbols
for (int i = 0; i < count; ++i)
{
BMSymbol sym = mSymbols[i];
// If the symbol's length is longer, move on
int symbolLength = sym.length;
if (symbolLength == 0 || textLength < symbolLength) continue;
bool match = true;
// Match the characters
for (int c = 0; c < symbolLength; ++c)
{
if (text[offset + c] != sym.sequence[c])
{
match = false;
break;
}
}
// Match found
if (match && sym.Validate(atlas)) return sym;
}
return null;
}
/// <summary>
/// Add a new symbol to the font.
/// </summary>
public void AddSymbol (string sequence, string spriteName)
{
BMSymbol symbol = GetSymbol(sequence, true);
symbol.spriteName = spriteName;
MarkAsChanged();
}
/// <summary>
/// Remove the specified symbol from the font.
/// </summary>
public void RemoveSymbol (string sequence)
{
BMSymbol symbol = GetSymbol(sequence, false);
if (symbol != null) symbols.Remove(symbol);
MarkAsChanged();
}
/// <summary>
/// Change an existing symbol's sequence to the specified value.
/// </summary>
public void RenameSymbol (string before, string after)
{
BMSymbol symbol = GetSymbol(before, false);
if (symbol != null) symbol.sequence = after;
MarkAsChanged();
}
/// <summary>
/// Whether the specified sprite is being used by the font.
/// </summary>
public bool UsesSprite (string s)
{
if (!string.IsNullOrEmpty(s))
{
if (s.Equals(spriteName))
return true;
for (int i = 0, imax = symbols.Count; i < imax; ++i)
{
BMSymbol sym = symbols[i];
if (s.Equals(sym.spriteName))
return true;
}
}
return false;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIFont.cs
|
C#
|
asf20
| 14,859
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Simple script that lets you localize a UIWidget.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(UIWidget))]
[AddComponentMenu("NGUI/UI/Localize")]
public class UILocalize : MonoBehaviour
{
/// <summary>
/// Localization key.
/// </summary>
public string key;
/// <summary>
/// Manually change the value of whatever the localization component is attached to.
/// </summary>
public string value
{
set
{
if (!string.IsNullOrEmpty(value))
{
UIWidget w = GetComponent<UIWidget>();
UILabel lbl = w as UILabel;
UISprite sp = w as UISprite;
if (lbl != null)
{
// If this is a label used by input, we should localize its default value instead
UIInput input = NGUITools.FindInParents<UIInput>(lbl.gameObject);
if (input != null && input.label == lbl) input.defaultText = value;
else lbl.text = value;
#if UNITY_EDITOR
if (!Application.isPlaying) NGUITools.SetDirty(lbl);
#endif
}
else if (sp != null)
{
sp.spriteName = value;
sp.MakePixelPerfect();
#if UNITY_EDITOR
if (!Application.isPlaying) NGUITools.SetDirty(sp);
#endif
}
}
}
}
bool mStarted = false;
/// <summary>
/// Localize the widget on enable, but only if it has been started already.
/// </summary>
void OnEnable ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (mStarted) OnLocalize();
}
/// <summary>
/// Localize the widget on start.
/// </summary>
void Start ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
mStarted = true;
OnLocalize();
}
/// <summary>
/// This function is called by the Localization manager via a broadcast SendMessage.
/// </summary>
void OnLocalize ()
{
// If no localization key has been specified, use the label's text as the key
if (string.IsNullOrEmpty(key))
{
UILabel lbl = GetComponent<UILabel>();
if (lbl != null) key = lbl.text;
}
// If we still don't have a key, leave the value as blank
if (!string.IsNullOrEmpty(key)) value = Localization.Get(key);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UILocalize.cs
|
C#
|
asf20
| 2,273
|
//--------------------------------------------
// NGUI: HUD Text
// Copyright © 2012 Tasharen Entertainment
//--------------------------------------------
using UnityEngine;
/// <summary>
/// Attaching this script to an object will make it visibly follow another object, even if the two are using different cameras to draw them.
/// </summary>
[AddComponentMenu("NGUI/Examples/Follow Target")]
public class UIFollowTarget : MonoBehaviour
{
/// <summary>
/// 3D target that this object will be positioned above.
/// </summary>
public Transform target;
/// <summary>
/// Whether the children will be disabled when this object is no longer visible.
/// </summary>
public bool disableIfInvisible = true;
Transform mTrans;
Camera mGameCamera;
Camera mUICamera;
//bool mIsVisible = false;
/// <summary>
/// Cache the transform;
/// </summary>
void Awake () { mTrans = transform; }
/// <summary>
/// Find both the UI camera and the game camera so they can be used for the position calculations
/// </summary>
void Start()
{
if (target != null)
{
mGameCamera = Camera.mainCamera;
if (mGameCamera == null)
{
if (GameObject.FindGameObjectWithTag("MainCamera") != null)
mGameCamera = GameObject.FindGameObjectWithTag("MainCamera").camera;
}
mUICamera = GameObject.FindObjectOfType<UICamera>().camera;
SetVisible(false);
}
else
{
//Debug.LogError("Expected to have 'target' set to a valid transform", this);
//enabled = false;
}
}
/// <summary>
/// Enable or disable child objects.
/// </summary>
void SetVisible (bool val)
{
//mIsVisible = val;
//Debug.LogWarning("Set Visible : " + val + mTrans.childCount);
for (int i = 0, imax = mTrans.childCount; i < imax; ++i)
{
NGUITools.SetActive(mTrans.GetChild(i).gameObject, val);
}
}
/// <summary>
/// Update the position of the HUD object every frame such that is position correctly over top of its real world object.
/// </summary>
void Update ()
{
if (target != null)
{
if (mGameCamera == null)
{
mGameCamera = Camera.mainCamera;
if (mGameCamera == null)
{
if (GameObject.FindGameObjectWithTag("MainCamera") != null)
mGameCamera = GameObject.FindObjectOfType<UICamera>().camera;
}
}
if(mUICamera == null)
{
mUICamera = GameObject.FindObjectOfType<UICamera>().camera;
}
//SetVisible(false);
}
else{
return;
}
Vector3 pos = mGameCamera.WorldToViewportPoint(target.position);
// Determine the visibility and the target alpha
bool isVisible = (pos.z > 0f && pos.x > 0f && pos.x < 1f && pos.y > 0f && pos.y < 1f);
// Update the visibility flag
//if (disableIfInvisible && mIsVisible != isVisible) SetVisible(isVisible);
SetVisible(isVisible);
//mTrans.localPosition = new Vector3( 1000.0f,1000.0f,1000.0f);
// If visible, update the position
if (isVisible)
{
Vector3 convert = mUICamera.ViewportToWorldPoint(pos);
transform.position = convert;
pos = mTrans.localPosition;
pos.x = Mathf.RoundToInt(pos.x);
pos.y = Mathf.RoundToInt(pos.y);
pos.z = 0f;
mTrans.localPosition = pos;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIFollowTarget.cs
|
C#
|
asf20
| 3,448
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This script can be used to stretch objects relative to the screen's width and height.
/// The most obvious use would be to create a full-screen background by attaching it to a sprite.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/Stretch")]
public class UIStretch : MonoBehaviour
{
public enum Style
{
None,
Horizontal,
Vertical,
Both,
BasedOnHeight,
FillKeepingRatio, // Fits the image so that it entirely fills the specified container keeping its ratio
FitInternalKeepingRatio // Fits the image/item inside of the specified container keeping its ratio
}
/// <summary>
/// Camera used to determine the anchor bounds. Set automatically if none was specified.
/// </summary>
public Camera uiCamera = null;
/// <summary>
/// Object used to determine the container's bounds. Overwrites the camera-based anchoring if the value was specified.
/// </summary>
public GameObject container = null;
/// <summary>
/// Stretching style.
/// </summary>
public Style style = Style.None;
/// <summary>
/// Whether the operation will occur only once and the script will then be disabled.
/// Screen size changes will still cause the script's logic to execute.
/// </summary>
public bool runOnlyOnce = true;
/// <summary>
/// Relative-to-target size.
/// </summary>
public Vector2 relativeSize = Vector2.one;
/// <summary>
/// The size that the item/image should start out initially.
/// Used for FillKeepingRatio, and FitInternalKeepingRatio.
/// Contributed by Dylan Ryan.
/// </summary>
public Vector2 initialSize = Vector2.one;
/// <summary>
/// Padding applied after the size of the stretched object gets calculated. This value is in pixels.
/// </summary>
public Vector2 borderPadding = Vector2.zero;
// Deprecated legacy functionality
[HideInInspector][SerializeField] UIWidget widgetContainer;
Transform mTrans;
UIWidget mWidget;
UISprite mSprite;
UIPanel mPanel;
UIRoot mRoot;
Animation mAnim;
Rect mRect;
bool mStarted = false;
void Awake ()
{
mAnim = animation;
mRect = new Rect();
mTrans = transform;
mWidget = GetComponent<UIWidget>();
mSprite = GetComponent<UISprite>();
mPanel = GetComponent<UIPanel>();
UICamera.onScreenResize += ScreenSizeChanged;
}
void OnDestroy () { UICamera.onScreenResize -= ScreenSizeChanged; }
void ScreenSizeChanged () { if (mStarted && runOnlyOnce) Update(); }
void Start ()
{
if (container == null && widgetContainer != null)
{
container = widgetContainer.gameObject;
widgetContainer = null;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
mRoot = NGUITools.FindInParents<UIRoot>(gameObject);
Update();
mStarted = true;
}
void Update ()
{
if (mAnim != null && mAnim.isPlaying) return;
if (style != Style.None)
{
UIWidget wc = (container == null) ? null : container.GetComponent<UIWidget>();
UIPanel pc = (container == null && wc == null) ? null : container.GetComponent<UIPanel>();
float adjustment = 1f;
if (wc != null)
{
Bounds b = wc.CalculateBounds(transform.parent);
mRect.x = b.min.x;
mRect.y = b.min.y;
mRect.width = b.size.x;
mRect.height = b.size.y;
}
else if (pc != null)
{
if (pc.clipping == UIDrawCall.Clipping.None)
{
// Panel has no clipping -- just use the screen's dimensions
float ratio = (mRoot != null) ? (float)mRoot.activeHeight / Screen.height * 0.5f : 0.5f;
mRect.xMin = -Screen.width * ratio;
mRect.yMin = -Screen.height * ratio;
mRect.xMax = -mRect.xMin;
mRect.yMax = -mRect.yMin;
}
else
{
// Panel has clipping -- use it as the mRect
Vector4 cr = pc.finalClipRegion;
mRect.x = cr.x - (cr.z * 0.5f);
mRect.y = cr.y - (cr.w * 0.5f);
mRect.width = cr.z;
mRect.height = cr.w;
}
}
else if (container != null)
{
Transform root = transform.parent;
Bounds b = (root != null) ? NGUIMath.CalculateRelativeWidgetBounds(root, container.transform) :
NGUIMath.CalculateRelativeWidgetBounds(container.transform);
mRect.x = b.min.x;
mRect.y = b.min.y;
mRect.width = b.size.x;
mRect.height = b.size.y;
}
else if (uiCamera != null)
{
mRect = uiCamera.pixelRect;
if (mRoot != null) adjustment = mRoot.pixelSizeAdjustment;
}
else return;
float rectWidth = mRect.width;
float rectHeight = mRect.height;
if (adjustment != 1f && rectHeight > 1f)
{
float scale = mRoot.activeHeight / rectHeight;
rectWidth *= scale;
rectHeight *= scale;
}
Vector3 size = (mWidget != null) ? new Vector3(mWidget.width, mWidget.height) : mTrans.localScale;
if (style == Style.BasedOnHeight)
{
size.x = relativeSize.x * rectHeight;
size.y = relativeSize.y * rectHeight;
}
else if (style == Style.FillKeepingRatio)
{
// Contributed by Dylan Ryan
float screenRatio = rectWidth / rectHeight;
float imageRatio = initialSize.x / initialSize.y;
if (imageRatio < screenRatio)
{
// Fit horizontally
float scale = rectWidth / initialSize.x;
size.x = rectWidth;
size.y = initialSize.y * scale;
}
else
{
// Fit vertically
float scale = rectHeight / initialSize.y;
size.x = initialSize.x * scale;
size.y = rectHeight;
}
}
else if (style == Style.FitInternalKeepingRatio)
{
// Contributed by Dylan Ryan
float screenRatio = rectWidth / rectHeight;
float imageRatio = initialSize.x / initialSize.y;
if (imageRatio > screenRatio)
{
// Fit horizontally
float scale = rectWidth / initialSize.x;
size.x = rectWidth;
size.y = initialSize.y * scale;
}
else
{
// Fit vertically
float scale = rectHeight / initialSize.y;
size.x = initialSize.x * scale;
size.y = rectHeight;
}
}
else
{
if (style != Style.Vertical)
size.x = relativeSize.x * rectWidth;
if (style != Style.Horizontal)
size.y = relativeSize.y * rectHeight;
}
if (mSprite != null)
{
float multiplier = (mSprite.atlas != null) ? mSprite.atlas.pixelSize : 1f;
size.x -= borderPadding.x * multiplier;
size.y -= borderPadding.y * multiplier;
if (style != Style.Vertical)
mSprite.width = Mathf.RoundToInt(size.x);
if (style != Style.Horizontal)
mSprite.height = Mathf.RoundToInt(size.y);
size = Vector3.one;
}
else if (mWidget != null)
{
if (style != Style.Vertical)
mWidget.width = Mathf.RoundToInt(size.x - borderPadding.x);
if (style != Style.Horizontal)
mWidget.height = Mathf.RoundToInt(size.y - borderPadding.y);
size = Vector3.one;
}
else if (mPanel != null)
{
Vector4 cr = mPanel.baseClipRegion;
if (style != Style.Vertical)
cr.z = size.x - borderPadding.x;
if (style != Style.Horizontal)
cr.w = size.y - borderPadding.y;
mPanel.baseClipRegion = cr;
size = Vector3.one;
}
else
{
if (style != Style.Vertical)
size.x -= borderPadding.x;
if (style != Style.Horizontal)
size.y -= borderPadding.y;
}
if (mTrans.localScale != size)
mTrans.localScale = size;
if (runOnlyOnce && Application.isPlaying) enabled = false;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIStretch.cs
|
C#
|
asf20
| 7,554
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This script can be used to restrict camera rendering to a specific part of the screen by specifying the two corners.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("NGUI/UI/Viewport Camera")]
public class UIViewport : MonoBehaviour
{
public Camera sourceCamera;
public Transform topLeft;
public Transform bottomRight;
public float fullSize = 1f;
Camera mCam;
void Start ()
{
mCam = camera;
if (sourceCamera == null) sourceCamera = Camera.main;
}
void LateUpdate ()
{
if (topLeft != null && bottomRight != null)
{
Vector3 tl = sourceCamera.WorldToScreenPoint(topLeft.position);
Vector3 br = sourceCamera.WorldToScreenPoint(bottomRight.position);
Rect rect = new Rect(tl.x / Screen.width, br.y / Screen.height,
(br.x - tl.x) / Screen.width, (tl.y - br.y) / Screen.height);
float size = fullSize * rect.height;
if (rect != mCam.rect) mCam.rect = rect;
if (mCam.orthographicSize != size) mCam.orthographicSize = size;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIViewport.cs
|
C#
|
asf20
| 1,235
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// This is a script used to keep the game object scaled to 2/(Screen.height).
/// If you use it, be sure to NOT use UIOrthoCamera at the same time.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/Root")]
public class UIRoot : MonoBehaviour
{
static public List<UIRoot> list = new List<UIRoot>();
/// <summary>
/// List of all UIRoots present in the scene.
/// </summary>
public enum Scaling
{
PixelPerfect,
FixedSize,
FixedSizeOnMobiles,
}
/// <summary>
/// Type of scaling used by the UIRoot.
/// </summary>
public Scaling scalingStyle = Scaling.PixelPerfect;
/// <summary>
/// Height of the screen when the scaling style is set to FixedSize.
/// </summary>
public int manualHeight = 720;
/// <summary>
/// If the screen height goes below this value, it will be as if the scaling style
/// is set to FixedSize with manualHeight of this value.
/// </summary>
public int minimumHeight = 320;
/// <summary>
/// If the screen height goes above this value, it will be as if the scaling style
/// is set to FixedSize with manualHeight of this value.
/// </summary>
public int maximumHeight = 1536;
/// <summary>
/// Whether the final value will be adjusted by the device's DPI setting.
/// </summary>
public bool adjustByDPI = false;
/// <summary>
/// If set and the game is in portrait mode, the UI will shrink based on the screen's width instead of height.
/// </summary>
public bool shrinkPortraitUI = false;
/// <summary>
/// UI Root's active height, based on the size of the screen.
/// </summary>
public int activeHeight
{
get
{
int h = Screen.height;
int height = Mathf.Max(2, h);
if (scalingStyle == Scaling.FixedSize) return manualHeight;
int w = Screen.width;
#if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_BLACKBERRY
if (scalingStyle == Scaling.FixedSizeOnMobiles)
return manualHeight;
#endif
if (height < minimumHeight) height = minimumHeight;
if (height > maximumHeight) height = maximumHeight;
// Portrait mode uses the maximum of width or height to shrink the UI
if (shrinkPortraitUI && h > w) height = Mathf.RoundToInt(height * ((float)h / w));
// Adjust the final value by the DPI setting
return adjustByDPI ? NGUIMath.AdjustByDPI(height) : height;
}
}
/// <summary>
/// Pixel size adjustment. Most of the time it's at 1, unless the scaling style is set to FixedSize.
/// </summary>
public float pixelSizeAdjustment { get { return GetPixelSizeAdjustment(Screen.height); } }
/// <summary>
/// Helper function that figures out the pixel size adjustment for the specified game object.
/// </summary>
static public float GetPixelSizeAdjustment (GameObject go)
{
UIRoot root = NGUITools.FindInParents<UIRoot>(go);
return (root != null) ? root.pixelSizeAdjustment : 1f;
}
/// <summary>
/// Calculate the pixel size adjustment at the specified screen height value.
/// </summary>
public float GetPixelSizeAdjustment (int height)
{
height = Mathf.Max(2, height);
if (scalingStyle == Scaling.FixedSize)
return (float)manualHeight / height;
#if UNITY_IPHONE || UNITY_ANDROID
if (scalingStyle == Scaling.FixedSizeOnMobiles)
return (float)manualHeight / height;
#endif
if (height < minimumHeight) return (float)minimumHeight / height;
if (height > maximumHeight) return (float)maximumHeight / height;
return 1f;
}
Transform mTrans;
protected virtual void Awake () { mTrans = transform; }
protected virtual void OnEnable () { list.Add(this); }
protected virtual void OnDisable () { list.Remove(this); }
protected virtual void Start ()
{
UIOrthoCamera oc = GetComponentInChildren<UIOrthoCamera>();
if (oc != null)
{
Debug.LogWarning("UIRoot should not be active at the same time as UIOrthoCamera. Disabling UIOrthoCamera.", oc);
Camera cam = oc.gameObject.GetComponent<Camera>();
oc.enabled = false;
if (cam != null) cam.orthographicSize = 1f;
}
else Update();
}
void Update ()
{
#if UNITY_EDITOR
if (!Application.isPlaying && gameObject.layer != 0)
UnityEditor.EditorPrefs.SetInt("NGUI Layer", gameObject.layer);
#endif
if (mTrans != null)
{
float calcActiveHeight = activeHeight;
if (calcActiveHeight > 0f )
{
float size = 2f / calcActiveHeight;
Vector3 ls = mTrans.localScale;
if (!(Mathf.Abs(ls.x - size) <= float.Epsilon) ||
!(Mathf.Abs(ls.y - size) <= float.Epsilon) ||
!(Mathf.Abs(ls.z - size) <= float.Epsilon))
{
mTrans.localScale = new Vector3(size, size, size);
}
}
}
}
/// <summary>
/// Broadcast the specified message to the entire UI.
/// </summary>
static public void Broadcast (string funcName)
{
#if UNITY_EDITOR
if (Application.isPlaying)
#endif
{
for (int i = 0, imax = list.Count; i < imax; ++i)
{
UIRoot root = list[i];
if (root != null) root.BroadcastMessage(funcName, SendMessageOptions.DontRequireReceiver);
}
}
}
/// <summary>
/// Broadcast the specified message to the entire UI.
/// </summary>
static public void Broadcast (string funcName, object param)
{
if (param == null)
{
// More on this: http://answers.unity3d.com/questions/55194/suggested-workaround-for-sendmessage-bug.html
Debug.LogError("SendMessage is bugged when you try to pass 'null' in the parameter field. It behaves as if no parameter was specified.");
}
else
{
for (int i = 0, imax = list.Count; i < imax; ++i)
{
UIRoot root = list[i];
if (root != null) root.BroadcastMessage(funcName, param, SendMessageOptions.DontRequireReceiver);
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIRoot.cs
|
C#
|
asf20
| 5,844
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// This script should be attached to each camera that's used to draw the objects with
/// UI components on them. This may mean only one camera (main camera or your UI camera),
/// or multiple cameras if you happen to have multiple viewports. Failing to attach this
/// script simply means that objects drawn by this camera won't receive UI notifications:
///
/// * OnHover (isOver) is sent when the mouse hovers over a collider or moves away.
/// * OnPress (isDown) is sent when a mouse button gets pressed on the collider.
/// * OnSelect (selected) is sent when a mouse button is released on the same object as it was pressed on.
/// * OnClick () is sent with the same conditions as OnSelect, with the added check to see if the mouse has not moved much.
/// UICamera.currentTouchID tells you which button was clicked.
/// * OnDoubleClick () is sent when the click happens twice within a fourth of a second.
/// UICamera.currentTouchID tells you which button was clicked.
///
/// * OnDragStart () is sent to a game object under the touch just before the OnDrag() notifications begin.
/// * OnDrag (delta) is sent to an object that's being dragged.
/// * OnDragOver (draggedObject) is sent to a game object when another object is dragged over its area.
/// * OnDragOut (draggedObject) is sent to a game object when another object is dragged out of its area.
/// * OnDragEnd () is sent to a dragged object when the drag event finishes.
///
/// * OnTooltip (show) is sent when the mouse hovers over a collider for some time without moving.
/// * OnScroll (float delta) is sent out when the mouse scroll wheel is moved.
/// * OnKey (KeyCode key) is sent when keyboard or controller input is used.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/NGUI Event System (UICamera)")]
[RequireComponent(typeof(Camera))]
public class UICamera : MonoBehaviour
{
public enum ControlScheme
{
Mouse,
Touch,
Controller,
}
/// <summary>
/// Whether the touch event will be sending out the OnClick notification at the end.
/// </summary>
public enum ClickNotification
{
None,
Always,
BasedOnDelta,
}
/// <summary>
/// Ambiguous mouse, touch, or controller event.
/// </summary>
public class MouseOrTouch
{
public Vector2 pos; // Current position of the mouse or touch event
public Vector2 lastPos; // Previous position of the mouse or touch event
public Vector2 delta; // Delta since last update
public Vector2 totalDelta; // Delta since the event started being tracked
public Camera pressedCam; // Camera that the OnPress(true) was fired with
public GameObject last; // Last object under the touch or mouse
public GameObject current; // Current game object under the touch or mouse
public GameObject pressed; // Last game object to receive OnPress
public GameObject dragged; // Game object that's being dragged
public float clickTime = 0f; // The last time a click event was sent out
public ClickNotification clickNotification = ClickNotification.Always;
public bool touchBegan = true;
public bool pressStarted = false;
public bool dragStarted = false;
}
/// <summary>
/// Camera type controls how raycasts are handled by the UICamera.
/// </summary>
public enum EventType
{
World, // Perform a Physics.Raycast and sort by distance to the point that was hit.
UI, // Perform a Physics.Raycast and sort by widget depth.
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
Unity2D, // Perform a Physics2D.OverlapPoint
#endif
}
/// <summary>
/// List of all active cameras in the scene.
/// </summary>
static public BetterList<UICamera> list = new BetterList<UICamera>();
public delegate void OnScreenResize ();
/// <summary>
/// Delegate triggered when the screen size changes for any reason.
/// Subscribe to it if you don't want to compare Screen.width and Screen.height each frame.
/// </summary>
static public OnScreenResize onScreenResize;
/// <summary>
/// Event type -- use "UI" for your user interfaces, and "World" for your game camera.
/// This setting changes how raycasts are handled. Raycasts have to be more complicated for UI cameras.
/// </summary>
public EventType eventType = EventType.UI;
/// <summary>
/// Which layers will receive events.
/// </summary>
public LayerMask eventReceiverMask = -1;
/// <summary>
/// If 'true', currently hovered object will be shown in the top left corner.
/// </summary>
public bool debug = false;
/// <summary>
/// Whether the mouse input is used.
/// </summary>
public bool useMouse = true;
/// <summary>
/// Whether the touch-based input is used.
/// </summary>
public bool useTouch = true;
/// <summary>
/// Whether multi-touch is allowed.
/// </summary>
public bool allowMultiTouch = true;
/// <summary>
/// Whether the keyboard events will be processed.
/// </summary>
public bool useKeyboard = true;
/// <summary>
/// Whether the joystick and controller events will be processed.
/// </summary>
public bool useController = true;
[System.Obsolete("Use new OnDragStart / OnDragOver / OnDragOut / OnDragEnd events instead")]
public bool stickyPress { get { return true; } }
/// <summary>
/// Whether the tooltip will disappear as soon as the mouse moves (false) or only if the mouse moves outside of the widget's area (true).
/// </summary>
public bool stickyTooltip = true;
/// <summary>
/// How long of a delay to expect before showing the tooltip.
/// </summary>
public float tooltipDelay = 1f;
/// <summary>
/// How much the mouse has to be moved after pressing a button before it starts to send out drag events.
/// </summary>
public float mouseDragThreshold = 4f;
/// <summary>
/// How far the mouse is allowed to move in pixels before it's no longer considered for click events, if the click notification is based on delta.
/// </summary>
public float mouseClickThreshold = 10f;
/// <summary>
/// How much the mouse has to be moved after pressing a button before it starts to send out drag events.
/// </summary>
public float touchDragThreshold = 40f;
/// <summary>
/// How far the touch is allowed to move in pixels before it's no longer considered for click events, if the click notification is based on delta.
/// </summary>
public float touchClickThreshold = 40f;
/// <summary>
/// Raycast range distance. By default it's as far as the camera can see.
/// </summary>
public float rangeDistance = -1f;
/// <summary>
/// Name of the axis used for scrolling.
/// </summary>
public string scrollAxisName = "Mouse ScrollWheel";
/// <summary>
/// Name of the axis used to send up and down key events.
/// </summary>
public string verticalAxisName = "Vertical";
/// <summary>
/// Name of the axis used to send left and right key events.
/// </summary>
public string horizontalAxisName = "Horizontal";
/// <summary>
/// Various keys used by the camera.
/// </summary>
public KeyCode submitKey0 = KeyCode.Return;
public KeyCode submitKey1 = KeyCode.JoystickButton0;
public KeyCode cancelKey0 = KeyCode.Escape;
public KeyCode cancelKey1 = KeyCode.JoystickButton1;
public delegate void OnCustomInput ();
/// <summary>
/// Custom input processing logic, if desired. For example: WP7 touches.
/// Use UICamera.current to get the current camera.
/// </summary>
static public OnCustomInput onCustomInput;
/// <summary>
/// Whether tooltips will be shown or not.
/// </summary>
static public bool showTooltips = true;
/// <summary>
/// Position of the last touch (or mouse) event.
/// </summary>
static public Vector2 lastTouchPosition = Vector2.zero;
/// <summary>
/// Last raycast hit prior to sending out the event. This is useful if you want detailed information
/// about what was actually hit in your OnClick, OnHover, and other event functions.
/// </summary>
static public RaycastHit lastHit;
/// <summary>
/// UICamera that sent out the event.
/// </summary>
static public UICamera current = null;
/// <summary>
/// Last camera active prior to sending out the event. This will always be the camera that actually sent out the event.
/// </summary>
static public Camera currentCamera = null;
/// <summary>
/// Current control scheme. Set automatically when events arrive.
/// </summary>
static public ControlScheme currentScheme = ControlScheme.Mouse;
/// <summary>
/// ID of the touch or mouse operation prior to sending out the event. Mouse ID is '-1' for left, '-2' for right mouse button, '-3' for middle.
/// </summary>
static public int currentTouchID = -1;
/// <summary>
/// Key that triggered the event, if any.
/// </summary>
static public KeyCode currentKey = KeyCode.None;
/// <summary>
/// Ray projected into the screen underneath the current touch.
/// </summary>
static public Ray currentRay
{
get
{
return (currentCamera != null && currentTouch != null) ?
currentCamera.ScreenPointToRay(currentTouch.pos) : new Ray();
}
}
/// <summary>
/// Current touch, set before any event function gets called.
/// </summary>
static public MouseOrTouch currentTouch = null;
/// <summary>
/// Whether an input field currently has focus.
/// </summary>
static public bool inputHasFocus = false;
/// <summary>
/// If set, this game object will receive all events regardless of whether they were handled or not.
/// </summary>
static public GameObject genericEventHandler;
/// <summary>
/// If events don't get handled, they will be forwarded to this game object.
/// </summary>
static public GameObject fallThrough;
// Selected widget (for input)
static GameObject mCurrentSelection = null;
static GameObject mNextSelection = null;
static ControlScheme mNextScheme = ControlScheme.Controller;
// Mouse events
static MouseOrTouch[] mMouse = new MouseOrTouch[] { new MouseOrTouch(), new MouseOrTouch(), new MouseOrTouch() };
// The last object to receive OnHover
static GameObject mHover;
// Joystick/controller/keyboard event
static public MouseOrTouch controller = new MouseOrTouch();
// Used to ensure that joystick-based controls don't trigger that often
static float mNextEvent = 0f;
// List of currently active touches
static Dictionary<int, MouseOrTouch> mTouches = new Dictionary<int, MouseOrTouch>();
// Used to detect screen dimension changes
static int mWidth = 0;
static int mHeight = 0;
// Tooltip widget (mouse only)
GameObject mTooltip = null;
// Mouse input is turned off on iOS
Camera mCam = null;
float mTooltipTime = 0f;
float mNextRaycast = 0f;
/// <summary>
/// Helper function that determines if this script should be handling the events.
/// </summary>
bool handlesEvents { get { return eventHandler == this; } }
/// <summary>
/// Caching is always preferable for performance.
/// </summary>
public Camera cachedCamera { get { if (mCam == null) mCam = camera; return mCam; } }
/// <summary>
/// Set to 'true' just before OnDrag-related events are sent. No longer needed, but kept for backwards compatibility.
/// </summary>
static public bool isDragging = false;
/// <summary>
/// The object hit by the last Raycast that was the result of a mouse or touch event.
/// </summary>
static public GameObject hoveredObject;
/// <summary>
/// Option to manually set the selected game object.
/// </summary>
static public GameObject selectedObject
{
get
{
return mCurrentSelection;
}
set
{
SetSelection(value, UICamera.currentScheme);
}
}
/// <summary>
/// Returns 'true' if any of the active touch, mouse or controller is currently holding the specified object.
/// </summary>
static public bool IsPressed (GameObject go)
{
for (int i = 0; i < 3; ++i) if (mMouse[i].pressed == go) return true;
foreach (KeyValuePair<int, MouseOrTouch> touch in mTouches) if (touch.Value.pressed == go) return true;
if (controller.pressed == go) return true;
return false;
}
/// <summary>
/// Change the selection.
/// </summary>
static protected void SetSelection (GameObject go, ControlScheme scheme)
{
if (mNextSelection != null)
{
mNextSelection = go;
}
else if (mCurrentSelection != go)
{
mNextSelection = go;
mNextScheme = scheme;
if (UICamera.list.size > 0)
{
UICamera cam = (mNextSelection != null) ? FindCameraForLayer(mNextSelection.layer) : UICamera.list[0];
if (cam != null) cam.StartCoroutine(cam.ChangeSelection());
}
}
}
/// <summary>
/// Selection change is delayed on purpose. This way selection changes during event processing won't cause
/// the newly selected widget to continue processing when it is it's turn. Example: pressing 'tab' on one
/// button selects the next button, and then it also processes its 'tab' in turn, selecting the next one.
/// </summary>
System.Collections.IEnumerator ChangeSelection ()
{
yield return new WaitForEndOfFrame();
Notify(mCurrentSelection, "OnSelect", false);
mCurrentSelection = mNextSelection;
mNextSelection = null;
if (mCurrentSelection != null)
{
current = this;
currentCamera = mCam;
UICamera.currentScheme = mNextScheme;
inputHasFocus = (mCurrentSelection.GetComponent<UIInput>() != null);
Notify(mCurrentSelection, "OnSelect", true);
current = null;
}
else inputHasFocus = false;
}
/// <summary>
/// Number of active touches from all sources.
/// </summary>
static public int touchCount
{
get
{
int count = 0;
foreach (KeyValuePair<int, MouseOrTouch> touch in mTouches)
if (touch.Value.pressed != null)
++count;
for (int i = 0; i < mMouse.Length; ++i)
if (mMouse[i].pressed != null)
++count;
if (controller.pressed != null)
++count;
return count;
}
}
/// <summary>
/// Number of active drag events from all sources.
/// </summary>
static public int dragCount
{
get
{
int count = 0;
foreach (KeyValuePair<int, MouseOrTouch> touch in mTouches)
if (touch.Value.dragged != null)
++count;
for (int i = 0; i < mMouse.Length; ++i)
if (mMouse[i].dragged != null)
++count;
if (controller.dragged != null)
++count;
return count;
}
}
/// <summary>
/// Convenience function that returns the main HUD camera.
/// </summary>
static public Camera mainCamera
{
get
{
UICamera mouse = eventHandler;
return (mouse != null) ? mouse.cachedCamera : null;
}
}
/// <summary>
/// Event handler for all types of events.
/// </summary>
static public UICamera eventHandler
{
get
{
for (int i = 0; i < list.size; ++i)
{
// Invalid or inactive entry -- keep going
UICamera cam = list.buffer[i];
if (cam == null || !cam.enabled || !NGUITools.GetActive(cam.gameObject)) continue;
return cam;
}
return null;
}
}
/// <summary>
/// Static comparison function used for sorting.
/// </summary>
static int CompareFunc (UICamera a, UICamera b)
{
if (a.cachedCamera.depth < b.cachedCamera.depth) return 1;
if (a.cachedCamera.depth > b.cachedCamera.depth) return -1;
return 0;
}
struct DepthEntry
{
public int depth;
public RaycastHit hit;
}
static DepthEntry mHit = new DepthEntry();
static BetterList<DepthEntry> mHits = new BetterList<DepthEntry>();
static RaycastHit mEmpty = new RaycastHit();
/// <summary>
/// Returns the object under the specified position.
/// </summary>
static public bool Raycast (Vector3 inPos, out RaycastHit hit)
{
for (int i = 0; i < list.size; ++i)
{
UICamera cam = list.buffer[i];
// Skip inactive scripts
if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) continue;
// Convert to view space
currentCamera = cam.cachedCamera;
Vector3 pos = currentCamera.ScreenToViewportPoint(inPos);
if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) continue;
// If it's outside the camera's viewport, do nothing
if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue;
// Cast a ray into the screen
Ray ray = currentCamera.ScreenPointToRay(inPos);
// Raycast into the screen
int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask;
float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane;
if (cam.eventType == EventType.World)
{
if (Physics.Raycast(ray, out hit, dist, mask))
{
hoveredObject = hit.collider.gameObject;
return true;
}
continue;
}
else if (cam.eventType == EventType.UI)
{
RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask);
if (hits.Length > 1)
{
for (int b = 0; b < hits.Length; ++b)
{
GameObject go = hits[b].collider.gameObject;
UIWidget w = go.GetComponent<UIWidget>();
if (w != null)
{
if (!w.isVisible) continue;
if (w.hitCheck != null && !w.hitCheck(hits[b].point)) continue;
}
else
{
UIRect rect = NGUITools.FindInParents<UIRect>(go);
if (rect != null && rect.finalAlpha < 0.001f) continue;
}
mHit.depth = NGUITools.CalculateRaycastDepth(go);
if (mHit.depth != int.MaxValue)
{
mHit.hit = hits[b];
mHits.Add(mHit);
}
}
mHits.Sort(delegate(DepthEntry r1, DepthEntry r2) { return r2.depth.CompareTo(r1.depth); });
for (int b = 0; b < mHits.size; ++b)
{
#if UNITY_FLASH
if (IsVisible(mHits.buffer[b]))
#else
if (IsVisible(ref mHits.buffer[b]))
#endif
{
hit = mHits[b].hit;
hoveredObject = hit.collider.gameObject;
mHits.Clear();
return true;
}
}
mHits.Clear();
}
else if (hits.Length == 1)
{
Collider c = hits[0].collider;
UIWidget w = c.GetComponent<UIWidget>();
if (w != null)
{
if (!w.isVisible) continue;
if (w.hitCheck != null && !w.hitCheck(hits[0].point)) continue;
}
else
{
UIRect rect = NGUITools.FindInParents<UIRect>(c.gameObject);
if (rect != null && rect.finalAlpha < 0.001f) continue;
}
if (IsVisible(ref hits[0]))
{
hit = hits[0];
hoveredObject = hit.collider.gameObject;
return true;
}
}
continue;
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
else if (cam.eventType == EventType.Unity2D)
{
if (m2DPlane.Raycast(ray, out dist))
{
Collider2D c2d = Physics2D.OverlapPoint(ray.GetPoint(dist), mask);
if (c2d)
{
hit = lastHit;
hit.point = pos;
hoveredObject = c2d.gameObject;
return true;
}
}
continue;
}
#endif
}
hit = mEmpty;
return false;
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
static Plane m2DPlane = new Plane(Vector3.back, 0f);
#endif
/// <summary>
/// Helper function to check if the specified hit is visible by the panel.
/// </summary>
static bool IsVisible (ref RaycastHit hit)
{
UIPanel panel = NGUITools.FindInParents<UIPanel>(hit.collider.gameObject);
while (panel != null)
{
if (!panel.IsVisible(hit.point)) return false;
panel = panel.parentPanel;
}
return true;
}
/// <summary>
/// Helper function to check if the specified hit is visible by the panel.
/// </summary>
#if UNITY_FLASH
static bool IsVisible (DepthEntry de)
#else
static bool IsVisible (ref DepthEntry de)
#endif
{
UIPanel panel = NGUITools.FindInParents<UIPanel>(de.hit.collider.gameObject);
while (panel != null)
{
if (!panel.IsVisible(de.hit.point)) return false;
panel = panel.parentPanel;
}
return true;
}
/// <summary>
/// Whether the specified object should be highlighted.
/// </summary>
static public bool IsHighlighted (GameObject go)
{
if (UICamera.currentScheme == UICamera.ControlScheme.Mouse)
return (UICamera.hoveredObject == go);
if (UICamera.currentScheme == UICamera.ControlScheme.Controller)
return (UICamera.selectedObject == go);
return false;
}
/// <summary>
/// Find the camera responsible for handling events on objects of the specified layer.
/// </summary>
static public UICamera FindCameraForLayer (int layer)
{
int layerMask = 1 << layer;
for (int i = 0; i < list.size; ++i)
{
UICamera cam = list.buffer[i];
Camera uc = cam.cachedCamera;
if ((uc != null) && (uc.cullingMask & layerMask) != 0) return cam;
}
return null;
}
/// <summary>
/// Using the keyboard will result in 1 or -1, depending on whether up or down keys have been pressed.
/// </summary>
static int GetDirection (KeyCode up, KeyCode down)
{
if (Input.GetKeyDown(up)) return 1;
if (Input.GetKeyDown(down)) return -1;
return 0;
}
/// <summary>
/// Using the keyboard will result in 1 or -1, depending on whether up or down keys have been pressed.
/// </summary>
static int GetDirection (KeyCode up0, KeyCode up1, KeyCode down0, KeyCode down1)
{
if (Input.GetKeyDown(up0) || Input.GetKeyDown(up1)) return 1;
if (Input.GetKeyDown(down0) || Input.GetKeyDown(down1)) return -1;
return 0;
}
/// <summary>
/// Using the joystick to move the UI results in 1 or -1 if the threshold has been passed, mimicking up/down keys.
/// </summary>
static int GetDirection (string axis)
{
float time = RealTime.time;
if (mNextEvent < time && !string.IsNullOrEmpty(axis))
{
float val = Input.GetAxis(axis);
if (val > 0.75f)
{
mNextEvent = time + 0.25f;
return 1;
}
if (val < -0.75f)
{
mNextEvent = time + 0.25f;
return -1;
}
}
return 0;
}
static bool mNotifying = false;
/// <summary>
/// Generic notification function. Used in place of SendMessage to shorten the code and allow for more than one receiver.
/// </summary>
static public void Notify (GameObject go, string funcName, object obj)
{
if (mNotifying) return;
mNotifying = true;
if (NGUITools.GetActive(go))
{
go.SendMessage(funcName, obj, SendMessageOptions.DontRequireReceiver);
if (genericEventHandler != null && genericEventHandler != go)
{
genericEventHandler.SendMessage(funcName, obj, SendMessageOptions.DontRequireReceiver);
}
}
mNotifying = false;
}
/// <summary>
/// Get the details of the specified mouse button.
/// </summary>
static public MouseOrTouch GetMouse (int button) { return mMouse[button]; }
/// <summary>
/// Get or create a touch event.
/// </summary>
static public MouseOrTouch GetTouch (int id)
{
MouseOrTouch touch = null;
if (id < 0) return GetMouse(-id - 1);
if (!mTouches.TryGetValue(id, out touch))
{
touch = new MouseOrTouch();
touch.touchBegan = true;
mTouches.Add(id, touch);
}
return touch;
}
/// <summary>
/// Remove a touch event from the list.
/// </summary>
static public void RemoveTouch (int id) { mTouches.Remove(id); }
/// <summary>
/// Add this camera to the list.
/// </summary>
void Awake ()
{
mWidth = Screen.width;
mHeight = Screen.height;
if (Application.platform == RuntimePlatform.Android ||
Application.platform == RuntimePlatform.IPhonePlayer
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1
|| Application.platform == RuntimePlatform.WP8Player
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3
|| Application.platform == RuntimePlatform.BB10Player
#else
|| Application.platform == RuntimePlatform.BlackBerryPlayer
#endif
#endif
)
{
useMouse = false;
useTouch = true;
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
useKeyboard = false;
useController = false;
}
}
else if (Application.platform == RuntimePlatform.PS3 ||
Application.platform == RuntimePlatform.XBOX360)
{
useMouse = false;
useTouch = false;
useKeyboard = false;
useController = true;
}
// Save the starting mouse position
mMouse[0].pos.x = Input.mousePosition.x;
mMouse[0].pos.y = Input.mousePosition.y;
for (int i = 1; i < 3; ++i)
{
mMouse[i].pos = mMouse[0].pos;
mMouse[i].lastPos = mMouse[0].pos;
}
lastTouchPosition = mMouse[0].pos;
}
/// <summary>
/// Sort the list when enabled.
/// </summary>
void OnEnable () { list.Add(this); list.Sort(CompareFunc); }
/// <summary>
/// Remove this camera from the list.
/// </summary>
void OnDisable () { list.Remove(this); }
#if !UNITY_3_5 && !UNITY_4_0
/// <summary>
/// We don't want the camera to send out any kind of mouse events.
/// </summary>
void Start ()
{
if (eventType != EventType.World && cachedCamera.transparencySortMode != TransparencySortMode.Orthographic)
cachedCamera.transparencySortMode = TransparencySortMode.Orthographic;
if (Application.isPlaying) cachedCamera.eventMask = 0;
if (handlesEvents) NGUIDebug.debugRaycast = debug;
}
#else
void Start () { if (handlesEvents) NGUIDebug.debugRaycast = debug; }
#endif
#if UNITY_EDITOR
void OnValidate () { Start(); }
#endif
/// <summary>
/// Check the input and send out appropriate events.
/// </summary>
void Update ()
{
// Only the first UI layer should be processing events
#if UNITY_EDITOR
if (!Application.isPlaying || !handlesEvents) return;
#else
if (!handlesEvents) return;
#endif
current = this;
// Process touch events first
if (useTouch) ProcessTouches ();
else if (useMouse) ProcessMouse();
// Custom input processing
if (onCustomInput != null) onCustomInput();
// Clear the selection on the cancel key, but only if mouse input is allowed
if (useMouse && mCurrentSelection != null)
{
if (cancelKey0 != KeyCode.None && Input.GetKeyDown(cancelKey0))
{
currentScheme = ControlScheme.Controller;
currentKey = cancelKey0;
selectedObject = null;
}
else if (cancelKey1 != KeyCode.None && Input.GetKeyDown(cancelKey1))
{
currentScheme = ControlScheme.Controller;
currentKey = cancelKey1;
selectedObject = null;
}
}
// If nothing is selected, input focus is lost
if (mCurrentSelection == null) inputHasFocus = false;
// Update the keyboard and joystick events
if (mCurrentSelection != null) ProcessOthers();
// If it's time to show a tooltip, inform the object we're hovering over
if (useMouse && mHover != null)
{
float scroll = !string.IsNullOrEmpty(scrollAxisName) ? Input.GetAxis(scrollAxisName) : 0f;
if (scroll != 0f) Notify(mHover, "OnScroll", scroll);
if (showTooltips && mTooltipTime != 0f && (mTooltipTime < RealTime.time ||
Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
{
mTooltip = mHover;
ShowTooltip(true);
}
}
current = null;
}
/// <summary>
/// Keep an eye on screen size changes.
/// </summary>
void LateUpdate ()
{
#if UNITY_EDITOR
if (!Application.isPlaying || !handlesEvents) return;
#else
if (!handlesEvents) return;
#endif
int w = Screen.width;
int h = Screen.height;
if (w != mWidth || h != mHeight)
{
mWidth = w;
mHeight = h;
UIRoot.Broadcast("UpdateAnchors");
if (onScreenResize != null)
onScreenResize();
}
}
/// <summary>
/// Update mouse input.
/// </summary>
public void ProcessMouse ()
{
// Update the position and delta
lastTouchPosition = Input.mousePosition;
mMouse[0].delta = lastTouchPosition - mMouse[0].pos;
mMouse[0].pos = lastTouchPosition;
bool posChanged = mMouse[0].delta.sqrMagnitude > 0.001f;
// Propagate the updates to the other mouse buttons
for (int i = 1; i < 3; ++i)
{
mMouse[i].pos = mMouse[0].pos;
mMouse[i].delta = mMouse[0].delta;
}
// Is any button currently pressed?
bool isPressed = false;
bool justPressed = false;
for (int i = 0; i < 3; ++i)
{
if (Input.GetMouseButtonDown(i))
{
currentScheme = ControlScheme.Mouse;
justPressed = true;
isPressed = true;
}
else if (Input.GetMouseButton(i))
{
currentScheme = ControlScheme.Mouse;
isPressed = true;
}
}
// No need to perform raycasts every frame
if (isPressed || posChanged || mNextRaycast < RealTime.time)
{
mNextRaycast = RealTime.time + 0.02f;
if (!Raycast(Input.mousePosition, out lastHit)) hoveredObject = fallThrough;
if (hoveredObject == null) hoveredObject = genericEventHandler;
for (int i = 0; i < 3; ++i) mMouse[i].current = hoveredObject;
}
bool highlightChanged = (mMouse[0].last != mMouse[0].current);
if (highlightChanged) currentScheme = ControlScheme.Mouse;
if (isPressed)
{
// A button was pressed -- cancel the tooltip
mTooltipTime = 0f;
}
else if (posChanged && (!stickyTooltip || highlightChanged))
{
if (mTooltipTime != 0f)
{
// Delay the tooltip
mTooltipTime = RealTime.time + tooltipDelay;
}
else if (mTooltip != null)
{
// Hide the tooltip
ShowTooltip(false);
}
}
// The button was released over a different object -- remove the highlight from the previous
if ((justPressed || !isPressed) && mHover != null && highlightChanged)
{
currentScheme = ControlScheme.Mouse;
if (mTooltip != null) ShowTooltip(false);
Notify(mHover, "OnHover", false);
mHover = null;
}
// Process all 3 mouse buttons as individual touches
for (int i = 0; i < 3; ++i)
{
bool pressed = Input.GetMouseButtonDown(i);
bool unpressed = Input.GetMouseButtonUp(i);
if (pressed || unpressed) currentScheme = ControlScheme.Mouse;
currentTouch = mMouse[i];
currentTouchID = -1 - i;
currentKey = KeyCode.Mouse0 + i;
// We don't want to update the last camera while there is a touch happening
if (pressed) currentTouch.pressedCam = currentCamera;
else if (currentTouch.pressed != null) currentCamera = currentTouch.pressedCam;
// Process the mouse events
ProcessTouch(pressed, unpressed);
currentKey = KeyCode.None;
}
currentTouch = null;
// If nothing is pressed and there is an object under the touch, highlight it
if (!isPressed && highlightChanged)
{
currentScheme = ControlScheme.Mouse;
mTooltipTime = RealTime.time + tooltipDelay;
mHover = mMouse[0].current;
Notify(mHover, "OnHover", true);
}
// Update the last value
mMouse[0].last = mMouse[0].current;
for (int i = 1; i < 3; ++i) mMouse[i].last = mMouse[0].last;
}
/// <summary>
/// Update touch-based events.
/// </summary>
public void ProcessTouches ()
{
currentScheme = ControlScheme.Touch;
for (int i = 0; i < Input.touchCount; ++i)
{
Touch touch = Input.GetTouch(i);
currentTouchID = allowMultiTouch ? touch.fingerId : 1;
currentTouch = GetTouch(currentTouchID);
bool pressed = (touch.phase == TouchPhase.Began) || currentTouch.touchBegan;
bool unpressed = (touch.phase == TouchPhase.Canceled) || (touch.phase == TouchPhase.Ended);
currentTouch.touchBegan = false;
// Although input.deltaPosition can be used, calculating it manually is safer (just in case)
currentTouch.delta = pressed ? Vector2.zero : touch.position - currentTouch.pos;
currentTouch.pos = touch.position;
// Raycast into the screen
if (!Raycast(currentTouch.pos, out lastHit)) hoveredObject = fallThrough;
if (hoveredObject == null) hoveredObject = genericEventHandler;
currentTouch.last = currentTouch.current;
currentTouch.current = hoveredObject;
lastTouchPosition = currentTouch.pos;
// We don't want to update the last camera while there is a touch happening
if (pressed) currentTouch.pressedCam = currentCamera;
else if (currentTouch.pressed != null) currentCamera = currentTouch.pressedCam;
// Double-tap support
if (touch.tapCount > 1) currentTouch.clickTime = RealTime.time;
// Process the events from this touch
ProcessTouch(pressed, unpressed);
// If the touch has ended, remove it from the list
if (unpressed) RemoveTouch(currentTouchID);
currentTouch.last = null;
currentTouch = null;
// Don't consider other touches
if (!allowMultiTouch) break;
}
if (Input.touchCount == 0)
{
if (useMouse) ProcessMouse();
#if UNITY_EDITOR
else ProcessFakeTouches();
#endif
}
}
/// <summary>
/// Process fake touch events where the mouse acts as a touch device.
/// Useful for testing mobile functionality in the editor.
/// </summary>
void ProcessFakeTouches ()
{
bool pressed = Input.GetMouseButtonDown(0);
bool unpressed = Input.GetMouseButtonUp(0);
bool held = Input.GetMouseButton(0);
if (pressed || unpressed || held)
{
currentTouchID = 1;
currentTouch = mMouse[0];
currentTouch.touchBegan = pressed;
Vector2 pos = Input.mousePosition;
currentTouch.delta = pressed ? Vector2.zero : pos - currentTouch.pos;
currentTouch.pos = pos;
// Raycast into the screen
if (!Raycast(currentTouch.pos, out lastHit)) hoveredObject = fallThrough;
if (hoveredObject == null) hoveredObject = genericEventHandler;
currentTouch.last = currentTouch.current;
currentTouch.current = hoveredObject;
lastTouchPosition = currentTouch.pos;
// We don't want to update the last camera while there is a touch happening
if (pressed) currentTouch.pressedCam = currentCamera;
else if (currentTouch.pressed != null) currentCamera = currentTouch.pressedCam;
// Process the events from this touch
ProcessTouch(pressed, unpressed);
// If the touch has ended, remove it from the list
if (unpressed) RemoveTouch(currentTouchID);
currentTouch.last = null;
currentTouch = null;
}
}
/// <summary>
/// Process keyboard and joystick events.
/// </summary>
public void ProcessOthers ()
{
currentTouchID = -100;
currentTouch = controller;
bool submitKeyDown = false;
bool submitKeyUp = false;
if (submitKey0 != KeyCode.None && Input.GetKeyDown(submitKey0))
{
currentKey = submitKey0;
submitKeyDown = true;
}
if (submitKey1 != KeyCode.None && Input.GetKeyDown(submitKey1))
{
currentKey = submitKey1;
submitKeyDown = true;
}
if (submitKey0 != KeyCode.None && Input.GetKeyUp(submitKey0))
{
currentKey = submitKey0;
submitKeyUp = true;
}
if (submitKey1 != KeyCode.None && Input.GetKeyUp(submitKey1))
{
currentKey = submitKey1;
submitKeyUp = true;
}
if (submitKeyDown || submitKeyUp)
{
currentScheme = ControlScheme.Controller;
currentTouch.last = currentTouch.current;
currentTouch.current = mCurrentSelection;
ProcessTouch(submitKeyDown, submitKeyUp);
currentTouch.last = null;
}
int vertical = 0;
int horizontal = 0;
if (useKeyboard)
{
if (inputHasFocus)
{
vertical += GetDirection(KeyCode.UpArrow, KeyCode.DownArrow);
horizontal += GetDirection(KeyCode.RightArrow, KeyCode.LeftArrow);
}
else
{
vertical += GetDirection(KeyCode.W, KeyCode.UpArrow, KeyCode.S, KeyCode.DownArrow);
horizontal += GetDirection(KeyCode.D, KeyCode.RightArrow, KeyCode.A, KeyCode.LeftArrow);
}
}
if (useController)
{
if (!string.IsNullOrEmpty(verticalAxisName)) vertical += GetDirection(verticalAxisName);
if (!string.IsNullOrEmpty(horizontalAxisName)) horizontal += GetDirection(horizontalAxisName);
}
// Send out key notifications
if (vertical != 0)
{
currentScheme = ControlScheme.Controller;
Notify(mCurrentSelection, "OnKey", vertical > 0 ? KeyCode.UpArrow : KeyCode.DownArrow);
}
if (horizontal != 0)
{
currentScheme = ControlScheme.Controller;
Notify(mCurrentSelection, "OnKey", horizontal > 0 ? KeyCode.RightArrow : KeyCode.LeftArrow);
}
if (useKeyboard && Input.GetKeyDown(KeyCode.Tab))
{
currentKey = KeyCode.Tab;
currentScheme = ControlScheme.Controller;
Notify(mCurrentSelection, "OnKey", KeyCode.Tab);
}
// Send out the cancel key notification
if (cancelKey0 != KeyCode.None && Input.GetKeyDown(cancelKey0))
{
currentKey = cancelKey0;
currentScheme = ControlScheme.Controller;
Notify(mCurrentSelection, "OnKey", KeyCode.Escape);
}
if (cancelKey1 != KeyCode.None && Input.GetKeyDown(cancelKey1))
{
currentKey = cancelKey1;
currentScheme = ControlScheme.Controller;
Notify(mCurrentSelection, "OnKey", KeyCode.Escape);
}
currentTouch = null;
currentKey = KeyCode.None;
}
/// <summary>
/// Process the events of the specified touch.
/// </summary>
public void ProcessTouch (bool pressed, bool unpressed)
{
// Whether we're using the mouse
bool isMouse = (currentScheme == ControlScheme.Mouse);
float drag = isMouse ? mouseDragThreshold : touchDragThreshold;
float click = isMouse ? mouseClickThreshold : touchClickThreshold;
// So we can use sqrMagnitude below
drag *= drag;
click *= click;
// Send out the press message
if (pressed)
{
if (mTooltip != null) ShowTooltip(false);
currentTouch.pressStarted = true;
Notify(currentTouch.pressed, "OnPress", false);
currentTouch.pressed = currentTouch.current;
currentTouch.dragged = currentTouch.current;
currentTouch.clickNotification = ClickNotification.BasedOnDelta;
currentTouch.totalDelta = Vector2.zero;
currentTouch.dragStarted = false;
Notify(currentTouch.pressed, "OnPress", true);
// Clear the selection
if (currentTouch.pressed != mCurrentSelection)
{
if (mTooltip != null) ShowTooltip(false);
currentScheme = ControlScheme.Touch;
selectedObject = null;
}
}
else if (currentTouch.pressed != null && (currentTouch.delta.sqrMagnitude != 0f || currentTouch.current != currentTouch.last))
{
// Keep track of the total movement
currentTouch.totalDelta += currentTouch.delta;
float mag = currentTouch.totalDelta.sqrMagnitude;
bool justStarted = false;
// If the drag process hasn't started yet but we've already moved off the object, start it immediately
if (!currentTouch.dragStarted && currentTouch.last != currentTouch.current)
{
currentTouch.dragStarted = true;
currentTouch.delta = currentTouch.totalDelta;
// OnDragOver is sent for consistency, so that OnDragOut is always preceded by OnDragOver
isDragging = true;
Notify(currentTouch.dragged, "OnDragStart", null);
Notify(currentTouch.last, "OnDragOver", currentTouch.dragged);
isDragging = false;
}
else if (!currentTouch.dragStarted && drag < mag)
{
// If the drag event has not yet started, see if we've dragged the touch far enough to start it
justStarted = true;
currentTouch.dragStarted = true;
currentTouch.delta = currentTouch.totalDelta;
}
// If we're dragging the touch, send out drag events
if (currentTouch.dragStarted)
{
if (mTooltip != null) ShowTooltip(false);
isDragging = true;
bool isDisabled = (currentTouch.clickNotification == ClickNotification.None);
if (justStarted)
{
Notify(currentTouch.dragged, "OnDragStart", null);
Notify(currentTouch.current, "OnDragOver", currentTouch.dragged);
}
else if (currentTouch.last != currentTouch.current)
{
Notify(currentTouch.last, "OnDragOut", currentTouch.dragged);
Notify(currentTouch.current, "OnDragOver", currentTouch.dragged);
}
Notify(currentTouch.dragged, "OnDrag", currentTouch.delta);
currentTouch.last = currentTouch.current;
isDragging = false;
if (isDisabled)
{
// If the notification status has already been disabled, keep it as such
currentTouch.clickNotification = ClickNotification.None;
}
else if (currentTouch.clickNotification == ClickNotification.BasedOnDelta && click < mag)
{
// We've dragged far enough to cancel the click
currentTouch.clickNotification = ClickNotification.None;
}
}
}
// Send out the unpress message
if (unpressed)
{
currentTouch.pressStarted = false;
if (mTooltip != null) ShowTooltip(false);
if (currentTouch.pressed != null)
{
// If there was a drag event in progress, make sure OnDragOut gets sent
if (currentTouch.dragStarted)
{
Notify(currentTouch.last, "OnDragOut", currentTouch.dragged);
Notify(currentTouch.dragged, "OnDragEnd", null);
}
// Send the notification of a touch ending
Notify(currentTouch.pressed, "OnPress", false);
// Send a hover message to the object
if (isMouse) Notify(currentTouch.current, "OnHover", true);
mHover = currentTouch.current;
// If the button/touch was released on the same object, consider it a click and select it
if (currentTouch.dragged == currentTouch.current ||
(currentScheme != ControlScheme.Controller &&
currentTouch.clickNotification != ClickNotification.None &&
currentTouch.totalDelta.sqrMagnitude < drag))
{
if (currentTouch.pressed != mCurrentSelection)
{
mNextSelection = null;
mCurrentSelection = currentTouch.pressed;
Notify(currentTouch.pressed, "OnSelect", true);
}
else
{
mNextSelection = null;
mCurrentSelection = currentTouch.pressed;
}
// If the touch should consider clicks, send out an OnClick notification
if (currentTouch.clickNotification != ClickNotification.None && currentTouch.pressed == currentTouch.current)
{
float time = RealTime.time;
Notify(currentTouch.pressed, "OnClick", null);
if (currentTouch.clickTime + 0.35f > time)
{
Notify(currentTouch.pressed, "OnDoubleClick", null);
}
currentTouch.clickTime = time;
}
}
else if (currentTouch.dragStarted) // The button/touch was released on a different object
{
// Send a drop notification (for drag & drop)
Notify(currentTouch.current, "OnDrop", currentTouch.dragged);
}
}
currentTouch.dragStarted = false;
currentTouch.pressed = null;
currentTouch.dragged = null;
}
}
/// <summary>
/// Show or hide the tooltip.
/// </summary>
public void ShowTooltip (bool val)
{
mTooltipTime = 0f;
Notify(mTooltip, "OnTooltip", val);
if (!val) mTooltip = null;
}
#if !UNITY_EDITOR
/// <summary>
/// Clear all active press states when the application gets paused.
/// </summary>
void OnApplicationPause ()
{
MouseOrTouch prev = currentTouch;
if (useTouch)
{
BetterList<int> ids = new BetterList<int>();
foreach (KeyValuePair<int, MouseOrTouch> pair in mTouches)
{
if (pair.Value != null && pair.Value.pressed)
{
currentTouch = pair.Value;
currentTouchID = pair.Key;
currentScheme = ControlScheme.Touch;
currentTouch.clickNotification = ClickNotification.None;
ProcessTouch(false, true);
ids.Add(currentTouchID);
}
}
for (int i = 0; i < ids.size; ++i)
RemoveTouch(ids[i]);
}
if (useMouse)
{
for (int i = 0; i < 3; ++i)
{
if (mMouse[i].pressed)
{
currentTouch = mMouse[i];
currentTouchID = -1 - i;
currentKey = KeyCode.Mouse0 + i;
currentScheme = ControlScheme.Mouse;
currentTouch.clickNotification = ClickNotification.None;
ProcessTouch(false, true);
}
}
}
if (useController)
{
if (controller.pressed)
{
currentTouch = controller;
currentTouchID = -100;
currentScheme = ControlScheme.Controller;
currentTouch.last = currentTouch.current;
currentTouch.current = mCurrentSelection;
currentTouch.clickNotification = ClickNotification.None;
ProcessTouch(false, true);
currentTouch.last = null;
}
}
currentTouch = prev;
}
#endif
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UICamera.cs
|
C#
|
asf20
| 43,311
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
using System;
[System.Serializable]
public class UISpriteData
{
public string name = "Sprite";
public int x = 0;
public int y = 0;
public int width = 0;
public int height = 0;
public int borderLeft = 0;
public int borderRight = 0;
public int borderTop = 0;
public int borderBottom = 0;
public int paddingLeft = 0;
public int paddingRight = 0;
public int paddingTop = 0;
public int paddingBottom = 0;
//bool rotated = false;
/// <summary>
/// Whether the sprite has a border.
/// </summary>
public bool hasBorder { get { return (borderLeft | borderRight | borderTop | borderBottom) != 0; } }
/// <summary>
/// Whether the sprite has been offset via padding.
/// </summary>
public bool hasPadding { get { return (paddingLeft | paddingRight | paddingTop | paddingBottom) != 0; } }
/// <summary>
/// Convenience function -- set the X, Y, width, and height.
/// </summary>
public void SetRect (int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/// <summary>
/// Convenience function -- set the sprite's padding.
/// </summary>
public void SetPadding (int left, int bottom, int right, int top)
{
paddingLeft = left;
paddingBottom = bottom;
paddingRight = right;
paddingTop = top;
}
/// <summary>
/// Convenience function -- set the sprite's border.
/// </summary>
public void SetBorder (int left, int bottom, int right, int top)
{
borderLeft = left;
borderBottom = bottom;
borderRight = right;
borderTop = top;
}
/// <summary>
/// Copy all values of the specified sprite data.
/// </summary>
public void CopyFrom (UISpriteData sd)
{
name = sd.name;
x = sd.x;
y = sd.y;
width = sd.width;
height = sd.height;
borderLeft = sd.borderLeft;
borderRight = sd.borderRight;
borderTop = sd.borderTop;
borderBottom = sd.borderBottom;
paddingLeft = sd.paddingLeft;
paddingRight = sd.paddingRight;
paddingTop = sd.paddingTop;
paddingBottom = sd.paddingBottom;
}
/// <summary>
/// Copy the border information from the specified sprite.
/// </summary>
public void CopyBorderFrom (UISpriteData sd)
{
borderLeft = sd.borderLeft;
borderRight = sd.borderRight;
borderTop = sd.borderTop;
borderBottom = sd.borderBottom;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UISpriteData.cs
|
C#
|
asf20
| 2,527
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// If you don't have or don't wish to create an atlas, you can simply use this script to draw a texture.
/// Keep in mind though that this will create an extra draw call with each UITexture present, so it's
/// best to use it only for backgrounds or temporary visible widgets.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/NGUI Texture")]
public class UITexture : UIWidget
{
public enum Flip
{
Nothing,
Horizontally,
Vertically,
Both,
}
[HideInInspector][SerializeField] Rect mRect = new Rect(0f, 0f, 1f, 1f);
[HideInInspector][SerializeField] Texture mTexture;
[HideInInspector][SerializeField] Material mMat;
[HideInInspector][SerializeField] Shader mShader;
[HideInInspector][SerializeField] Flip mFlip = Flip.Nothing;
int mPMA = -1;
/// <summary>
/// Texture used by the UITexture. You can set it directly, without the need to specify a material.
/// </summary>
public override Texture mainTexture
{
get
{
return mTexture;
}
set
{
if (mTexture != value)
{
RemoveFromPanel();
mTexture = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Material used by the widget.
/// </summary>
public override Material material
{
get
{
return mMat;
}
set
{
if (mMat != value)
{
RemoveFromPanel();
mShader = null;
mMat = value;
mPMA = -1;
MarkAsChanged();
}
}
}
/// <summary>
/// Shader used by the texture when creating a dynamic material (when the texture was specified, but the material was not).
/// </summary>
public override Shader shader
{
get
{
if (mMat != null) return mMat.shader;
if (mShader == null) mShader = Shader.Find("Unlit/Transparent Colored");
return mShader;
}
set
{
if (mShader != value)
{
RemoveFromPanel();
mShader = value;
mPMA = -1;
mMat = null;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite texture setting.
/// </summary>
public Flip flip
{
get
{
return mFlip;
}
set
{
if (mFlip != value)
{
mFlip = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Whether the texture is using a premultiplied alpha material.
/// </summary>
public bool premultipliedAlpha
{
get
{
if (mPMA == -1)
{
Material mat = material;
mPMA = (mat != null && mat.shader != null && mat.shader.name.Contains("Premultiplied")) ? 1 : 0;
}
return (mPMA == 1);
}
}
/// <summary>
/// UV rectangle used by the texture.
/// </summary>
public Rect uvRect
{
get
{
return mRect;
}
set
{
if (mRect != value)
{
mRect = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Widget's dimensions used for drawing. X = left, Y = bottom, Z = right, W = top.
/// This function automatically adds 1 pixel on the edge if the texture's dimensions are not even.
/// It's used to achieve pixel-perfect sprites even when an odd dimension widget happens to be centered.
/// </summary>
public override Vector4 drawingDimensions
{
get
{
Vector2 offset = pivotOffset;
float x0 = -offset.x * mWidth;
float y0 = -offset.y * mHeight;
float x1 = x0 + mWidth;
float y1 = y0 + mHeight;
Texture tex = mainTexture;
int w = (tex != null) ? tex.width : mWidth;
int h = (tex != null) ? tex.height : mHeight;
if ((w & 1) != 0) x1 -= (1f / w) * mWidth;
if ((h & 1) != 0) y1 -= (1f / h) * mHeight;
return new Vector4(
mDrawRegion.x == 0f ? x0 : Mathf.Lerp(x0, x1, mDrawRegion.x),
mDrawRegion.y == 0f ? y0 : Mathf.Lerp(y0, y1, mDrawRegion.y),
mDrawRegion.z == 1f ? x1 : Mathf.Lerp(x0, x1, mDrawRegion.z),
mDrawRegion.w == 1f ? y1 : Mathf.Lerp(y0, y1, mDrawRegion.w));
}
}
/// <summary>
/// Adjust the scale of the widget to make it pixel-perfect.
/// </summary>
public override void MakePixelPerfect ()
{
Texture tex = mainTexture;
if (tex != null)
{
int x = tex.width;
if ((x & 1) == 1) ++x;
int y = tex.height;
if ((y & 1) == 1) ++y;
width = x;
height = y;
}
base.MakePixelPerfect();
}
/// <summary>
/// Virtual function called by the UIPanel that fills the buffers.
/// </summary>
public override void OnFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Color colF = color;
colF.a = finalAlpha;
Color32 col = premultipliedAlpha ? NGUITools.ApplyPMA(colF) : colF;
Vector4 v = drawingDimensions;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
if (mFlip == Flip.Horizontally)
{
uvs.Add(new Vector2(mRect.xMax, mRect.yMin));
uvs.Add(new Vector2(mRect.xMax, mRect.yMax));
uvs.Add(new Vector2(mRect.xMin, mRect.yMax));
uvs.Add(new Vector2(mRect.xMin, mRect.yMin));
}
else if (mFlip == Flip.Vertically)
{
uvs.Add(new Vector2(mRect.xMin, mRect.yMax));
uvs.Add(new Vector2(mRect.xMin, mRect.yMin));
uvs.Add(new Vector2(mRect.xMax, mRect.yMin));
uvs.Add(new Vector2(mRect.xMax, mRect.yMax));
}
else if (mFlip == Flip.Both)
{
uvs.Add(new Vector2(mRect.xMax, mRect.yMin));
uvs.Add(new Vector2(mRect.xMax, mRect.yMax));
uvs.Add(new Vector2(mRect.xMin, mRect.yMax));
uvs.Add(new Vector2(mRect.xMin, mRect.yMin));
}
else
{
uvs.Add(new Vector2(mRect.xMin, mRect.yMin));
uvs.Add(new Vector2(mRect.xMin, mRect.yMax));
uvs.Add(new Vector2(mRect.xMax, mRect.yMax));
uvs.Add(new Vector2(mRect.xMax, mRect.yMin));
}
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UITexture.cs
|
C#
|
asf20
| 5,794
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_EDITOR && (UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_BLACKBERRY)
#define MOBILE
#endif
using UnityEngine;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Input field makes it possible to enter custom information within the UI.
/// </summary>
[AddComponentMenu("NGUI/UI/Input Field")]
public class UIInput : MonoBehaviour
{
public enum InputType
{
Standard,
AutoCorrect,
Password,
}
public enum Validation
{
None,
Integer,
Float,
Alphanumeric,
Username,
Name,
}
public enum KeyboardType
{
Default = 0,
ASCIICapable = 1,
NumbersAndPunctuation = 2,
URL = 3,
NumberPad = 4,
PhonePad = 5,
NamePhonePad = 6,
EmailAddress = 7,
}
public delegate char OnValidate (string text, int charIndex, char addedChar);
/// <summary>
/// Currently active input field. Only valid during callbacks.
/// </summary>
static public UIInput current;
/// <summary>
/// Currently selected input field, if any.
/// </summary>
static public UIInput selection;
/// <summary>
/// Text label used to display the input's value.
/// </summary>
public UILabel label;
/// <summary>
/// Type of data expected by the input field.
/// </summary>
public InputType inputType = InputType.Standard;
/// <summary>
/// Keyboard type applies to mobile keyboards that get shown.
/// </summary>
public KeyboardType keyboardType = KeyboardType.Default;
/// <summary>
/// What kind of validation to use with the input field's data.
/// </summary>
public Validation validation = Validation.None;
/// <summary>
/// Maximum number of characters allowed before input no longer works.
/// </summary>
public int characterLimit = 0;
/// <summary>
/// Field in player prefs used to automatically save the value.
/// </summary>
public string savedAs;
/// <summary>
/// Object to select when Tab key gets pressed.
/// </summary>
public GameObject selectOnTab;
/// <summary>
/// Color of the label when the input field has focus.
/// </summary>
public Color activeTextColor = Color.white;
/// <summary>
/// Color used by the caret symbol.
/// </summary>
public Color caretColor = new Color(1f, 1f, 1f, 0.8f);
/// <summary>
/// Color used by the selection rectangle.
/// </summary>
public Color selectionColor = new Color(1f, 223f / 255f, 141f / 255f, 0.5f);
/// <summary>
/// Event delegates triggered when the input field submits its data.
/// </summary>
public List<EventDelegate> onSubmit = new List<EventDelegate>();
/// <summary>
/// Event delegates triggered when the input field's text changes for any reason.
/// </summary>
public List<EventDelegate> onChange = new List<EventDelegate>();
/// <summary>
/// Custom validation callback.
/// </summary>
public OnValidate onValidate;
/// <summary>
/// Input field's value.
/// </summary>
[SerializeField][HideInInspector] protected string mValue;
protected string mDefaultText = "";
protected Color mDefaultColor = Color.white;
protected float mPosition = 0f;
protected bool mDoInit = true;
protected UIWidget.Pivot mPivot = UIWidget.Pivot.TopLeft;
protected bool mLoadSavedValue = true;
static protected int mDrawStart = 0;
#if MOBILE
static protected TouchScreenKeyboard mKeyboard;
#else
protected int mSelectionStart = 0;
protected int mSelectionEnd = 0;
protected UITexture mHighlight = null;
protected UITexture mCaret = null;
protected Texture2D mBlankTex = null;
protected float mNextBlink = 0f;
protected float mLastAlpha = 0f;
static protected string mLastIME = "";
#endif
/// <summary>
/// Default text used by the input's label.
/// </summary>
public string defaultText
{
get
{
return mDefaultText;
}
set
{
if (mDoInit) Init();
mDefaultText = value;
UpdateLabel();
}
}
[System.Obsolete("Use UIInput.value instead")]
public string text { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Input field's current text value.
/// </summary>
public string value
{
get
{
#if UNITY_EDITOR
if (!Application.isPlaying) return "";
#endif
if (mDoInit) Init();
return mValue;
}
set
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (mDoInit) Init();
mDrawStart = 0;
#if MOBILE && !UNITY_3_5
// BB10's implementation has a bug in Unity
if (Application.platform == RuntimePlatform.BB10Player)
value = value.Replace("\\b", "\b");
#endif
// Validate all input
value = Validate(value);
#if MOBILE
if (isSelected && mKeyboard != null && mCached != value)
{
mKeyboard.text = value;
mCached = value;
}
if (mValue != value)
{
mValue = value;
mLoadSavedValue = false;
if (!isSelected) SaveToPlayerPrefs(value);
UpdateLabel();
ExecuteOnChange();
}
#else
if (mValue != value)
{
mValue = value;
mLoadSavedValue = false;
if (isSelected)
{
if (string.IsNullOrEmpty(value))
{
mSelectionStart = 0;
mSelectionEnd = 0;
}
else
{
mSelectionStart = value.Length;
mSelectionEnd = mSelectionStart;
}
}
else SaveToPlayerPrefs(value);
UpdateLabel();
ExecuteOnChange();
}
#endif
}
}
[System.Obsolete("Use UIInput.isSelected instead")]
public bool selected { get { return isSelected; } set { isSelected = value; } }
/// <summary>
/// Whether the input is currently selected.
/// </summary>
public bool isSelected
{
get
{
return selection == this;
}
set
{
if (!value) { if (isSelected) UICamera.selectedObject = null; }
else UICamera.selectedObject = gameObject;
}
}
#if MOBILE
/// <summary>
/// Current position of the cursor.
/// </summary>
public int cursorPosition { get { return value.Length; } set {} }
/// <summary>
/// Index of the character where selection begins.
/// </summary>
public int selectionStart { get { return value.Length; } set {} }
/// <summary>
/// Index of the character where selection ends.
/// </summary>
public int selectionEnd { get { return value.Length; } set {} }
/// <summary>
/// Caret, in case it's needed.
/// </summary>
public UITexture caret { get { return null; } }
#else
/// <summary>
/// Current position of the cursor.
/// </summary>
public int cursorPosition
{
get
{
return isSelected ? mSelectionEnd : value.Length;
}
set
{
if (isSelected)
{
mSelectionEnd = value;
UpdateLabel();
}
}
}
/// <summary>
/// Index of the character where selection begins.
/// </summary>
public int selectionStart
{
get
{
return isSelected ? mSelectionStart : value.Length;
}
set
{
if (isSelected)
{
mSelectionStart = value;
UpdateLabel();
}
}
}
/// <summary>
/// Index of the character where selection ends.
/// </summary>
public int selectionEnd
{
get
{
return isSelected ? mSelectionEnd : value.Length;
}
set
{
if (isSelected)
{
mSelectionEnd = value;
UpdateLabel();
}
}
}
/// <summary>
/// Caret, in case it's needed.
/// </summary>
public UITexture caret { get { return mCaret; } }
#endif
/// <summary>
/// Validate the specified text, returning the validated version.
/// </summary>
public string Validate (string val)
{
if (string.IsNullOrEmpty(val)) return "";
StringBuilder sb = new StringBuilder(val.Length);
for (int i = 0; i < val.Length; ++i)
{
char c = val[i];
if (onValidate != null) c = onValidate(sb.ToString(), sb.Length, c);
else if (validation != Validation.None) c = Validate(sb.ToString(), sb.Length, c);
if (c != 0) sb.Append(c);
}
if (characterLimit > 0 && sb.Length > characterLimit)
return sb.ToString(0, characterLimit);
return sb.ToString();
}
/// <summary>
/// Automatically set the value by loading it from player prefs if possible.
/// </summary>
void Start ()
{
if (mLoadSavedValue) LoadValue();
else value = mValue.Replace("\\n", "\n");
}
/// <summary>
/// Labels used for input shouldn't support rich text.
/// </summary>
protected void Init ()
{
if (mDoInit && label != null)
{
mDoInit = false;
mDefaultText = label.text;
mDefaultColor = label.color;
label.supportEncoding = false;
if (label.alignment == NGUIText.Alignment.Justified)
{
label.alignment = NGUIText.Alignment.Left;
Debug.LogWarning("Input fields using labels with justified alignment are not supported at this time", this);
}
mPivot = label.pivot;
mPosition = label.cachedTransform.localPosition.x;
UpdateLabel();
}
}
/// <summary>
/// Save the specified value to player prefs.
/// </summary>
protected void SaveToPlayerPrefs (string val)
{
if (!string.IsNullOrEmpty(savedAs))
{
if (string.IsNullOrEmpty(val)) PlayerPrefs.DeleteKey(savedAs);
else PlayerPrefs.SetString(savedAs, val);
}
}
/// <summary>
/// Selection event, sent by the EventSystem.
/// </summary>
protected virtual void OnSelect (bool isSelected)
{
if (isSelected) OnSelectEvent();
else OnDeselectEvent();
}
/// <summary>
/// Notification of the input field gaining selection.
/// </summary>
protected void OnSelectEvent ()
{
selection = this;
if (mDoInit) Init();
if (label != null && NGUITools.GetActive(this))
{
label.color = activeTextColor;
#if MOBILE
if (Application.platform == RuntimePlatform.IPhonePlayer ||
Application.platform == RuntimePlatform.Android
#if UNITY_WP8
|| Application.platform == RuntimePlatform.WP8Player
#endif
#if UNITY_BLACKBERRY
|| Application.platform == RuntimePlatform.BB10Player
#endif
)
{
mKeyboard = (inputType == InputType.Password) ?
TouchScreenKeyboard.Open(mValue, TouchScreenKeyboardType.Default, false, false, true) :
TouchScreenKeyboard.Open(mValue, (TouchScreenKeyboardType)((int)keyboardType), inputType == InputType.AutoCorrect, label.multiLine, false, false, defaultText);
}
else
#endif
{
Vector2 pos = (UICamera.current != null && UICamera.current.cachedCamera != null) ?
UICamera.current.cachedCamera.WorldToScreenPoint(label.worldCorners[0]) :
label.worldCorners[0];
pos.y = Screen.height - pos.y;
Input.imeCompositionMode = IMECompositionMode.On;
Input.compositionCursorPos = pos;
#if !MOBILE
mSelectionStart = 0;
mSelectionEnd = string.IsNullOrEmpty(mValue) ? 0 : mValue.Length;
#endif
mDrawStart = 0;
}
UpdateLabel();
}
}
/// <summary>
/// Notification of the input field losing selection.
/// </summary>
protected void OnDeselectEvent ()
{
if (mDoInit) Init();
if (label != null && NGUITools.GetActive(this))
{
mValue = value;
#if MOBILE
if (mKeyboard != null)
{
mKeyboard.active = false;
mKeyboard = null;
}
#endif
if (string.IsNullOrEmpty(mValue))
{
label.text = mDefaultText;
label.color = mDefaultColor;
}
else label.text = mValue;
Input.imeCompositionMode = IMECompositionMode.Auto;
RestoreLabelPivot();
}
selection = null;
UpdateLabel();
}
/// <summary>
/// Update the text based on input.
/// </summary>
#if MOBILE
string mCached = "";
void Update()
{
if (mKeyboard != null && isSelected)
{
string text = mKeyboard.text;
if (mCached != text)
{
mCached = text;
value = text;
}
if (mKeyboard.done)
{
#if !UNITY_3_5
if (!mKeyboard.wasCanceled)
#endif
Submit();
mKeyboard = null;
isSelected = false;
mCached = "";
}
}
}
#else
void Update ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (isSelected)
{
if (mDoInit) Init();
if (selectOnTab != null && Input.GetKeyDown(KeyCode.Tab))
{
UICamera.selectedObject = selectOnTab;
return;
}
string ime = Input.compositionString;
// There seems to be an inconsistency between IME on Windows, and IME on OSX.
// On Windows, Input.inputString is always empty while IME is active. On the OSX it is not.
if (string.IsNullOrEmpty(ime) && !string.IsNullOrEmpty(Input.inputString))
{
// Process input ignoring non-printable characters as they are not consistent.
// Windows has them, OSX may not. They get handled inside OnGUI() instead.
string s = Input.inputString;
for (int i = 0; i < s.Length; ++i)
{
char ch = s[i];
if (ch < ' ') continue;
// OSX inserts these characters for arrow keys
if (ch == '\uF700') continue;
if (ch == '\uF701') continue;
if (ch == '\uF702') continue;
if (ch == '\uF703') continue;
Insert(ch.ToString());
}
}
// Append IME composition
if (mLastIME != ime)
{
mSelectionEnd = string.IsNullOrEmpty(ime) ? mSelectionStart : mValue.Length + ime.Length;
mLastIME = ime;
UpdateLabel();
ExecuteOnChange();
}
// Blink the caret
if (mCaret != null && mNextBlink < RealTime.time)
{
mNextBlink = RealTime.time + 0.5f;
mCaret.enabled = !mCaret.enabled;
}
// If the label's final alpha changes, we need to update the drawn geometry,
// or the highlight widgets (which have their geometry set manually) won't update.
if (isSelected && mLastAlpha != label.finalAlpha)
UpdateLabel();
}
}
/// <summary>
/// Unfortunately Unity 4.3 and earlier doesn't offer a way to properly process events outside of OnGUI.
/// </summary>
void OnGUI ()
{
if (isSelected && Event.current.rawType == EventType.KeyDown)
ProcessEvent(Event.current);
}
/// <summary>
/// Handle the specified event.
/// </summary>
bool ProcessEvent (Event ev)
{
if (label == null) return false;
RuntimePlatform rp = Application.platform;
bool isMac = (
rp == RuntimePlatform.OSXEditor ||
rp == RuntimePlatform.OSXPlayer ||
rp == RuntimePlatform.OSXWebPlayer);
bool ctrl = isMac ?
((ev.modifiers & EventModifiers.Command) != 0) :
((ev.modifiers & EventModifiers.Control) != 0);
bool shift = ((ev.modifiers & EventModifiers.Shift) != 0);
switch (ev.keyCode)
{
case KeyCode.Backspace:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
if (mSelectionStart == mSelectionEnd)
{
if (mSelectionStart < 1) return true;
--mSelectionEnd;
}
Insert("");
}
return true;
}
case KeyCode.Delete:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
if (mSelectionStart == mSelectionEnd)
{
if (mSelectionStart >= mValue.Length) return true;
++mSelectionEnd;
}
Insert("");
}
return true;
}
case KeyCode.LeftArrow:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
mSelectionEnd = Mathf.Max(mSelectionEnd - 1, 0);
if (!shift) mSelectionStart = mSelectionEnd;
UpdateLabel();
}
return true;
}
case KeyCode.RightArrow:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
mSelectionEnd = Mathf.Min(mSelectionEnd + 1, mValue.Length);
if (!shift) mSelectionStart = mSelectionEnd;
UpdateLabel();
}
return true;
}
case KeyCode.PageUp:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
mSelectionEnd = 0;
if (!shift) mSelectionStart = mSelectionEnd;
UpdateLabel();
}
return true;
}
case KeyCode.PageDown:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
mSelectionEnd = mValue.Length;
if (!shift) mSelectionStart = mSelectionEnd;
UpdateLabel();
}
return true;
}
case KeyCode.Home:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
if (label.multiLine)
{
mSelectionEnd = label.GetCharacterIndex(mSelectionEnd, KeyCode.Home);
}
else mSelectionEnd = 0;
if (!shift) mSelectionStart = mSelectionEnd;
UpdateLabel();
}
return true;
}
case KeyCode.End:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
if (label.multiLine)
{
mSelectionEnd = label.GetCharacterIndex(mSelectionEnd, KeyCode.End);
}
else mSelectionEnd = mValue.Length;
if (!shift) mSelectionStart = mSelectionEnd;
UpdateLabel();
}
return true;
}
case KeyCode.UpArrow:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
mSelectionEnd = label.GetCharacterIndex(mSelectionEnd, KeyCode.UpArrow);
if (mSelectionEnd != 0) mSelectionEnd += mDrawStart;
if (!shift) mSelectionStart = mSelectionEnd;
UpdateLabel();
}
return true;
}
case KeyCode.DownArrow:
{
ev.Use();
if (!string.IsNullOrEmpty(mValue))
{
mSelectionEnd = label.GetCharacterIndex(mSelectionEnd, KeyCode.DownArrow);
if (mSelectionEnd != label.processedText.Length) mSelectionEnd += mDrawStart;
else mSelectionEnd = mValue.Length;
if (!shift) mSelectionStart = mSelectionEnd;
UpdateLabel();
}
return true;
}
// Copy
case KeyCode.C:
{
if (ctrl)
{
ev.Use();
NGUITools.clipboard = GetSelection();
}
return true;
}
// Paste
case KeyCode.V:
{
if (ctrl)
{
ev.Use();
Insert(NGUITools.clipboard);
}
return true;
}
// Cut
case KeyCode.X:
{
if (ctrl)
{
ev.Use();
NGUITools.clipboard = GetSelection();
Insert("");
}
return true;
}
// Submit
case KeyCode.Return:
case KeyCode.KeypadEnter:
{
ev.Use();
if (label.multiLine && !ctrl && label.overflowMethod != UILabel.Overflow.ClampContent && validation == Validation.None)
{
Insert("\n");
}
else
{
UICamera.currentScheme = UICamera.ControlScheme.Controller;
UICamera.currentKey = ev.keyCode;
Submit();
UICamera.currentKey = KeyCode.None;
}
return true;
}
}
return false;
}
/// <summary>
/// Insert the specified text string into the current input value, respecting selection and validation.
/// </summary>
protected virtual void Insert (string text)
{
string left = GetLeftText();
string right = GetRightText();
int rl = right.Length;
StringBuilder sb = new StringBuilder(left.Length + right.Length + text.Length);
sb.Append(left);
// Append the new text
for (int i = 0, imax = text.Length; i < imax; ++i)
{
// Can't go past the character limit
if (characterLimit > 0 && sb.Length + rl >= characterLimit) break;
// If we have an input validator, validate the input first
char c = text[i];
if (onValidate != null) c = onValidate(sb.ToString(), sb.Length, c);
else if (validation != Validation.None) c = Validate(sb.ToString(), sb.Length, c);
// Append the character if it hasn't been invalidated
if (c != 0) sb.Append(c);
}
// Advance the selection
mSelectionStart = sb.Length;
mSelectionEnd = mSelectionStart;
// Append the text that follows it, ensuring that it's also validated after the inserted value
for (int i = 0, imax = right.Length; i < imax; ++i)
{
char c = right[i];
if (onValidate != null) c = onValidate(sb.ToString(), sb.Length, c);
else if (validation != Validation.None) c = Validate(sb.ToString(), sb.Length, c);
if (c != 0) sb.Append(c);
}
mValue = sb.ToString();
UpdateLabel();
ExecuteOnChange();
}
/// <summary>
/// Get the text to the left of the selection.
/// </summary>
protected string GetLeftText ()
{
int min = Mathf.Min(mSelectionStart, mSelectionEnd);
return (string.IsNullOrEmpty(mValue) || min < 0) ? "" : mValue.Substring(0, min);
}
/// <summary>
/// Get the text to the right of the selection.
/// </summary>
protected string GetRightText ()
{
int max = Mathf.Max(mSelectionStart, mSelectionEnd);
return (string.IsNullOrEmpty(mValue) || max >= mValue.Length) ? "" : mValue.Substring(max);
}
/// <summary>
/// Get currently selected text.
/// </summary>
protected string GetSelection ()
{
if (string.IsNullOrEmpty(mValue) || mSelectionStart == mSelectionEnd)
{
return "";
}
else
{
int min = Mathf.Min(mSelectionStart, mSelectionEnd);
int max = Mathf.Max(mSelectionStart, mSelectionEnd);
return mValue.Substring(min, max - min);
}
}
/// <summary>
/// Helper function that retrieves the index of the character under the mouse.
/// </summary>
protected int GetCharUnderMouse ()
{
Vector3[] corners = label.worldCorners;
Ray ray = UICamera.currentRay;
Plane p = new Plane(corners[0], corners[1], corners[2]);
float dist;
return p.Raycast(ray, out dist) ? mDrawStart + label.GetCharacterIndexAtPosition(ray.GetPoint(dist)) : 0;
}
/// <summary>
/// Move the caret on press.
/// </summary>
protected virtual void OnPress (bool isPressed)
{
if (isPressed && isSelected && label != null && UICamera.currentScheme == UICamera.ControlScheme.Mouse)
{
mSelectionEnd = GetCharUnderMouse();
if (!Input.GetKey(KeyCode.LeftShift) &&
!Input.GetKey(KeyCode.RightShift)) mSelectionStart = mSelectionEnd;
UpdateLabel();
}
}
/// <summary>
/// Drag selection.
/// </summary>
protected virtual void OnDrag (Vector2 delta)
{
if (label != null && UICamera.currentScheme == UICamera.ControlScheme.Mouse)
{
mSelectionEnd = GetCharUnderMouse();
UpdateLabel();
}
}
/// <summary>
/// Ensure we've released the dynamically created resources.
/// </summary>
void OnDisable () { Cleanup(); }
/// <summary>
/// Cleanup.
/// </summary>
protected virtual void Cleanup ()
{
if (mHighlight) mHighlight.enabled = false;
if (mCaret) mCaret.enabled = false;
if (mBlankTex)
{
NGUITools.Destroy(mBlankTex);
mBlankTex = null;
}
}
#endif // !MOBILE
/// <summary>
/// Submit the input field's text.
/// </summary>
public void Submit ()
{
if (NGUITools.GetActive(this))
{
mValue = value;
if (current == null)
{
current = this;
EventDelegate.Execute(onSubmit);
current = null;
}
SaveToPlayerPrefs(mValue);
}
}
/// <summary>
/// Update the visual text label.
/// </summary>
public void UpdateLabel ()
{
if (label != null)
{
if (mDoInit) Init();
bool selected = isSelected;
string fullText = value;
bool isEmpty = string.IsNullOrEmpty(fullText) && string.IsNullOrEmpty(Input.compositionString);
label.color = (isEmpty && !selected) ? mDefaultColor : activeTextColor;
string processed;
if (isEmpty)
{
processed = selected ? "" : mDefaultText;
RestoreLabelPivot();
}
else
{
if (inputType == InputType.Password)
{
processed = "";
string asterisk = "*";
if (label.bitmapFont != null && label.bitmapFont.bmFont != null &&
label.bitmapFont.bmFont.GetGlyph('*') == null) asterisk = "x";
for (int i = 0, imax = fullText.Length; i < imax; ++i) processed += asterisk;
}
else processed = fullText;
// Start with text leading up to the selection
int selPos = selected ? Mathf.Min(processed.Length, cursorPosition) : 0;
string left = processed.Substring(0, selPos);
// Append the composition string and the cursor character
if (selected) left += Input.compositionString;
// Append the text from the selection onwards
processed = left + processed.Substring(selPos, processed.Length - selPos);
// Clamped content needs to be adjusted further
if (selected && label.overflowMethod == UILabel.Overflow.ClampContent)
{
// Determine what will actually fit into the given line
int offset = label.CalculateOffsetToFit(processed);
if (offset == 0)
{
mDrawStart = 0;
RestoreLabelPivot();
}
else if (selPos < mDrawStart)
{
mDrawStart = selPos;
SetPivotToLeft();
}
else if (offset < mDrawStart)
{
mDrawStart = offset;
SetPivotToLeft();
}
else
{
offset = label.CalculateOffsetToFit(processed.Substring(0, selPos));
if (offset > mDrawStart)
{
mDrawStart = offset;
SetPivotToRight();
}
}
// If necessary, trim the front
if (mDrawStart != 0)
processed = processed.Substring(mDrawStart, processed.Length - mDrawStart);
}
else
{
mDrawStart = 0;
RestoreLabelPivot();
}
}
label.text = processed;
#if !MOBILE
if (selected)
{
int start = mSelectionStart - mDrawStart;
int end = mSelectionEnd - mDrawStart;
// Blank texture used by selection and caret
if (mBlankTex == null)
{
mBlankTex = new Texture2D(2, 2, TextureFormat.ARGB32, false);
for (int y = 0; y < 2; ++y)
for (int x = 0; x < 2; ++x)
mBlankTex.SetPixel(x, y, Color.white);
mBlankTex.Apply();
}
// Create the selection highlight
if (start != end)
{
if (mHighlight == null)
{
mHighlight = NGUITools.AddWidget<UITexture>(label.cachedGameObject);
mHighlight.name = "Input Highlight";
mHighlight.mainTexture = mBlankTex;
mHighlight.fillGeometry = false;
mHighlight.pivot = label.pivot;
mHighlight.SetAnchor(label.cachedTransform);
}
else
{
mHighlight.pivot = label.pivot;
mHighlight.mainTexture = mBlankTex;
mHighlight.MarkAsChanged();
mHighlight.enabled = true;
}
}
// Create the caret
if (mCaret == null)
{
mCaret = NGUITools.AddWidget<UITexture>(label.cachedGameObject);
mCaret.name = "Input Caret";
mCaret.mainTexture = mBlankTex;
mCaret.fillGeometry = false;
mCaret.pivot = label.pivot;
mCaret.SetAnchor(label.cachedTransform);
}
else
{
mCaret.pivot = label.pivot;
mCaret.mainTexture = mBlankTex;
mCaret.MarkAsChanged();
mCaret.enabled = true;
}
if (start != end)
{
label.PrintOverlay(start, end, mCaret.geometry, mHighlight.geometry, caretColor, selectionColor);
mHighlight.enabled = mHighlight.geometry.hasVertices;
}
else
{
label.PrintOverlay(start, end, mCaret.geometry, null, caretColor, selectionColor);
if (mHighlight != null) mHighlight.enabled = false;
}
// Reset the blinking time
mNextBlink = RealTime.time + 0.5f;
mLastAlpha = label.finalAlpha;
}
else Cleanup();
#endif
}
}
/// <summary>
/// Set the label's pivot to the left.
/// </summary>
protected void SetPivotToLeft ()
{
Vector2 po = NGUIMath.GetPivotOffset(mPivot);
po.x = 0f;
label.pivot = NGUIMath.GetPivot(po);
}
/// <summary>
/// Set the label's pivot to the right.
/// </summary>
protected void SetPivotToRight ()
{
Vector2 po = NGUIMath.GetPivotOffset(mPivot);
po.x = 1f;
label.pivot = NGUIMath.GetPivot(po);
}
/// <summary>
/// Restore the input label's pivot point.
/// </summary>
protected void RestoreLabelPivot ()
{
if (label != null && label.pivot != mPivot)
label.pivot = mPivot;
}
/// <summary>
/// Validate the specified input.
/// </summary>
protected char Validate (string text, int pos, char ch)
{
// Validation is disabled
if (validation == Validation.None || !enabled) return ch;
if (validation == Validation.Integer)
{
// Integer number validation
if (ch >= '0' && ch <= '9') return ch;
if (ch == '-' && pos == 0 && !text.Contains("-")) return ch;
}
else if (validation == Validation.Float)
{
// Floating-point number
if (ch >= '0' && ch <= '9') return ch;
if (ch == '-' && pos == 0 && !text.Contains("-")) return ch;
if (ch == '.' && !text.Contains(".")) return ch;
}
else if (validation == Validation.Alphanumeric)
{
// All alphanumeric characters
if (ch >= 'A' && ch <= 'Z') return ch;
if (ch >= 'a' && ch <= 'z') return ch;
if (ch >= '0' && ch <= '9') return ch;
}
else if (validation == Validation.Username)
{
// Lowercase and numbers
if (ch >= 'A' && ch <= 'Z') return (char)(ch - 'A' + 'a');
if (ch >= 'a' && ch <= 'z') return ch;
if (ch >= '0' && ch <= '9') return ch;
}
else if (validation == Validation.Name)
{
char lastChar = (text.Length > 0) ? text[Mathf.Clamp(pos, 0, text.Length - 1)] : ' ';
char nextChar = (text.Length > 0) ? text[Mathf.Clamp(pos + 1, 0, text.Length - 1)] : '\n';
if (ch >= 'a' && ch <= 'z')
{
// Space followed by a letter -- make sure it's capitalized
if (lastChar == ' ') return (char)(ch - 'a' + 'A');
return ch;
}
else if (ch >= 'A' && ch <= 'Z')
{
// Uppercase letters are only allowed after spaces (and apostrophes)
if (lastChar != ' ' && lastChar != '\'') return (char)(ch - 'A' + 'a');
return ch;
}
else if (ch == '\'')
{
// Don't allow more than one apostrophe
if (lastChar != ' ' && lastChar != '\'' && nextChar != '\'' && !text.Contains("'")) return ch;
}
else if (ch == ' ')
{
// Don't allow more than one space in a row
if (lastChar != ' ' && lastChar != '\'' && nextChar != ' ' && nextChar != '\'') return ch;
}
}
return (char)0;
}
/// <summary>
/// Execute the OnChange callback.
/// </summary>
protected void ExecuteOnChange ()
{
if (current == null && EventDelegate.IsValid(onChange))
{
current = this;
EventDelegate.Execute(onChange);
current = null;
}
}
/// <summary>
/// Convenience function to be used as a callback that will clear the input field's focus.
/// </summary>
public void RemoveFocus () { isSelected = false; }
/// <summary>
/// Convenience function that can be used as a callback for On Change notification.
/// </summary>
public void SaveValue () { SaveToPlayerPrefs(mValue); }
/// <summary>
/// Convenience function that can forcefully reset the input field's value to what was saved earlier.
/// </summary>
public void LoadValue ()
{
if (!string.IsNullOrEmpty(savedAs) && PlayerPrefs.HasKey(savedAs))
value = PlayerPrefs.GetString(savedAs);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIInput.cs
|
C#
|
asf20
| 29,874
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Convenience script that resizes the camera's orthographic size to match the screen size.
/// This script can be used to create pixel-perfect UI, however it's usually more convenient
/// to create the UI that stays proportional as the screen scales. If that is what you
/// want, you don't need this script (or at least don't need it to be active).
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("NGUI/UI/Orthographic Camera")]
public class UIOrthoCamera : MonoBehaviour
{
Camera mCam;
Transform mTrans;
void Start ()
{
mCam = camera;
mTrans = transform;
mCam.orthographic = true;
}
void Update ()
{
float y0 = mCam.rect.yMin * Screen.height;
float y1 = mCam.rect.yMax * Screen.height;
float size = (y1 - y0) * 0.5f * mTrans.lossyScale.y;
if (!Mathf.Approximately(mCam.orthographicSize, size)) mCam.orthographicSize = size;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIOrthoCamera.cs
|
C#
|
asf20
| 1,118
|
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Example script that can be used to show tooltips.
/// </summary>
[AddComponentMenu("NGUI/UI/Tooltip")]
public class UITooltip : MonoBehaviour
{
static protected UITooltip mInstance;
public Camera uiCamera;
public UILabel text;
public UISprite background;
public float appearSpeed = 10f;
public bool scalingTransitions = true;
protected Transform mTrans;
protected float mTarget = 0f;
protected float mCurrent = 0f;
protected Vector3 mPos;
protected Vector3 mSize = Vector3.zero;
protected UIWidget[] mWidgets;
/// <summary>
/// Whether the tooltip is currently visible.
/// </summary>
static public bool isVisible { get { return (mInstance != null && mInstance.mTarget == 1f); } }
void Awake () { mInstance = this; }
void OnDestroy () { mInstance = null; }
/// <summary>
/// Get a list of widgets underneath the tooltip.
/// </summary>
protected virtual void Start ()
{
mTrans = transform;
mWidgets = GetComponentsInChildren<UIWidget>();
mPos = mTrans.localPosition;
if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
SetAlpha(0f);
}
/// <summary>
/// Update the tooltip's alpha based on the target value.
/// </summary>
protected virtual void Update ()
{
if (mCurrent != mTarget)
{
mCurrent = Mathf.Lerp(mCurrent, mTarget, RealTime.deltaTime * appearSpeed);
if (Mathf.Abs(mCurrent - mTarget) < 0.001f) mCurrent = mTarget;
SetAlpha(mCurrent * mCurrent);
if (scalingTransitions)
{
Vector3 offset = mSize * 0.25f;
offset.y = -offset.y;
Vector3 size = Vector3.one * (1.5f - mCurrent * 0.5f);
Vector3 pos = Vector3.Lerp(mPos - offset, mPos, mCurrent);
mTrans.localPosition = pos;
mTrans.localScale = size;
}
}
}
/// <summary>
/// Set the alpha of all widgets.
/// </summary>
protected virtual void SetAlpha (float val)
{
for (int i = 0, imax = mWidgets.Length; i < imax; ++i)
{
UIWidget w = mWidgets[i];
Color c = w.color;
c.a = val;
w.color = c;
}
}
/// <summary>
/// Set the tooltip's text to the specified string.
/// </summary>
protected virtual void SetText (string tooltipText)
{
if (text != null && !string.IsNullOrEmpty(tooltipText))
{
mTarget = 1f;
if (text != null) text.text = tooltipText;
// Orthographic camera positioning is trivial
mPos = Input.mousePosition;
Transform textTrans = text.transform;
Vector3 offset = textTrans.localPosition;
Vector3 textScale = textTrans.localScale;
// Calculate the dimensions of the printed text
mSize = text.printedSize;
// Scale by the transform and adjust by the padding offset
mSize.x *= textScale.x;
mSize.y *= textScale.y;
if (background != null)
{
Vector4 border = background.border;
mSize.x += border.x + border.z + ( offset.x - border.x) * 2f;
mSize.y += border.y + border.w + (-offset.y - border.y) * 2f;
background.width = Mathf.RoundToInt(mSize.x);
background.height = Mathf.RoundToInt(mSize.y);
}
if (uiCamera != null)
{
// Since the screen can be of different than expected size, we want to convert
// mouse coordinates to view space, then convert that to world position.
mPos.x = Mathf.Clamp01(mPos.x / Screen.width);
mPos.y = Mathf.Clamp01(mPos.y / Screen.height);
// Calculate the ratio of the camera's target orthographic size to current screen size
float activeSize = uiCamera.orthographicSize / mTrans.parent.lossyScale.y;
float ratio = (Screen.height * 0.5f) / activeSize;
// Calculate the maximum on-screen size of the tooltip window
Vector2 max = new Vector2(ratio * mSize.x / Screen.width, ratio * mSize.y / Screen.height);
// Limit the tooltip to always be visible
mPos.x = Mathf.Min(mPos.x, 1f - max.x);
mPos.y = Mathf.Max(mPos.y, max.y);
// Update the absolute position and save the local one
mTrans.position = uiCamera.ViewportToWorldPoint(mPos);
mPos = mTrans.localPosition;
mPos.x = Mathf.Round(mPos.x);
mPos.y = Mathf.Round(mPos.y);
mTrans.localPosition = mPos;
}
else
{
// Don't let the tooltip leave the screen area
if (mPos.x + mSize.x > Screen.width) mPos.x = Screen.width - mSize.x;
if (mPos.y - mSize.y < 0f) mPos.y = mSize.y;
// Simple calculation that assumes that the camera is of fixed size
mPos.x -= Screen.width * 0.5f;
mPos.y -= Screen.height * 0.5f;
}
}
else mTarget = 0f;
}
/// <summary>
/// Show a tooltip with the specified text.
/// </summary>
static public void ShowText (string tooltipText)
{
if (mInstance != null)
{
mInstance.SetText(tooltipText);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UITooltip.cs
|
C#
|
asf20
| 4,706
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_FLASH
#define DYNAMIC_FONT
#endif
using UnityEngine;
using System.Collections.Generic;
using System;
using Alignment = NGUIText.Alignment;
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/NGUI Label")]
public class UILabel : UIWidget
{
public enum Effect
{
None,
Shadow,
Outline,
}
public enum Overflow
{
ShrinkContent,
ClampContent,
ResizeFreely,
ResizeHeight,
}
public enum Crispness
{
Never,
OnDesktop,
Always,
}
/// <summary>
/// Whether the label will keep its content crisp even when shrunk.
/// You may want to turn this off on mobile devices.
/// </summary>
public Crispness keepCrispWhenShrunk = Crispness.OnDesktop;
[HideInInspector][SerializeField] Font mTrueTypeFont;
[HideInInspector][SerializeField] UIFont mFont;
#if !UNITY_3_5
[MultilineAttribute(6)]
#endif
[HideInInspector][SerializeField] string mText = "";
[HideInInspector][SerializeField] int mFontSize = 16;
[HideInInspector][SerializeField] FontStyle mFontStyle = FontStyle.Normal;
[HideInInspector][SerializeField] Alignment mAlignment = Alignment.Automatic;
[HideInInspector][SerializeField] bool mEncoding = true;
[HideInInspector][SerializeField] int mMaxLineCount = 0; // 0 denotes unlimited
[HideInInspector][SerializeField] Effect mEffectStyle = Effect.None;
[HideInInspector][SerializeField] Color mEffectColor = Color.black;
[HideInInspector][SerializeField] NGUIText.SymbolStyle mSymbols = NGUIText.SymbolStyle.Normal;
[HideInInspector][SerializeField] Vector2 mEffectDistance = Vector2.one;
[HideInInspector][SerializeField] Overflow mOverflow = Overflow.ShrinkContent;
[HideInInspector][SerializeField] Material mMaterial;
[HideInInspector][SerializeField] bool mApplyGradient = false;
[HideInInspector][SerializeField] Color mGradientTop = Color.white;
[HideInInspector][SerializeField] Color mGradientBottom = new Color(0.7f, 0.7f, 0.7f);
[HideInInspector][SerializeField] int mSpacingX = 0;
[HideInInspector][SerializeField] int mSpacingY = 0;
// Obsolete values
[HideInInspector][SerializeField] bool mShrinkToFit = false;
[HideInInspector][SerializeField] int mMaxLineWidth = 0;
[HideInInspector][SerializeField] int mMaxLineHeight = 0;
[HideInInspector][SerializeField] float mLineWidth = 0;
[HideInInspector][SerializeField] bool mMultiline = true;
#if DYNAMIC_FONT
[System.NonSerialized]
Font mActiveTTF = null;
float mDensity = 1f;
#endif
bool mShouldBeProcessed = true;
string mProcessedText = null;
bool mPremultiply = false;
Vector2 mCalculatedSize = Vector2.zero;
float mScale = 1f;
int mPrintedSize = 0;
int mLastWidth = 0;
int mLastHeight = 0;
/// <summary>
/// Function used to determine if something has changed (and thus the geometry must be rebuilt)
/// </summary>
bool shouldBeProcessed
{
get
{
return mShouldBeProcessed;
}
set
{
if (value)
{
mChanged = true;
mShouldBeProcessed = true;
}
else
{
mShouldBeProcessed = false;
}
}
}
/// <summary>
/// Whether the rectangle is anchored horizontally.
/// </summary>
public override bool isAnchoredHorizontally { get { return base.isAnchoredHorizontally || mOverflow == Overflow.ResizeFreely; } }
/// <summary>
/// Whether the rectangle is anchored vertically.
/// </summary>
public override bool isAnchoredVertically
{
get
{
return base.isAnchoredVertically ||
mOverflow == Overflow.ResizeFreely ||
mOverflow == Overflow.ResizeHeight;
}
}
/// <summary>
/// Retrieve the material used by the font.
/// </summary>
public override Material material
{
get
{
if (mMaterial != null) return mMaterial;
if (mFont != null) return mFont.material;
if (mTrueTypeFont != null) return mTrueTypeFont.material;
return null;
}
set
{
if (mMaterial != value)
{
MarkAsChanged();
mMaterial = value;
MarkAsChanged();
}
}
}
[Obsolete("Use UILabel.bitmapFont instead")]
public UIFont font { get { return bitmapFont; } set { bitmapFont = value; } }
/// <summary>
/// Set the font used by this label.
/// </summary>
public UIFont bitmapFont
{
get
{
return mFont;
}
set
{
if (mFont != value)
{
RemoveFromPanel();
mFont = value;
mTrueTypeFont = null;
MarkAsChanged();
}
}
}
/// <summary>
/// Set the font used by this label.
/// </summary>
public Font trueTypeFont
{
get
{
if (mTrueTypeFont != null) return mTrueTypeFont;
return (mFont != null ? mFont.dynamicFont : null);
}
set
{
if (mTrueTypeFont != value)
{
#if DYNAMIC_FONT
SetActiveFont(null);
RemoveFromPanel();
mTrueTypeFont = value;
shouldBeProcessed = true;
mFont = null;
SetActiveFont(value);
ProcessAndRequest();
if (mActiveTTF != null)
base.MarkAsChanged();
#else
mTrueTypeFont = value;
mFont = null;
#endif
}
}
}
/// <summary>
/// Ambiguous helper function.
/// </summary>
public UnityEngine.Object ambigiousFont
{
get
{
return (mFont != null) ? (UnityEngine.Object)mFont : (UnityEngine.Object)mTrueTypeFont;
}
set
{
UIFont bf = value as UIFont;
if (bf != null) bitmapFont = bf;
else trueTypeFont = value as Font;
}
}
/// <summary>
/// Text that's being displayed by the label.
/// </summary>
public string text
{
get
{
return mText;
}
set
{
if (mText == value) return;
if (string.IsNullOrEmpty(value))
{
if (!string.IsNullOrEmpty(mText))
{
mText = "";
shouldBeProcessed = true;
ProcessAndRequest();
}
}
else if (mText != value)
{
mText = value;
shouldBeProcessed = true;
ProcessAndRequest();
}
if (autoResizeBoxCollider) ResizeCollider();
}
}
/// <summary>
/// Default font size.
/// </summary>
public int defaultFontSize { get { return (trueTypeFont != null) ? mFontSize : (mFont != null ? mFont.defaultSize : 16); } }
/// <summary>
/// Active font size used by the label.
/// </summary>
public int fontSize
{
get
{
return mFontSize;
}
set
{
value = Mathf.Clamp(value, 0, 256);
if (mFontSize != value)
{
mFontSize = value;
shouldBeProcessed = true;
ProcessAndRequest();
}
}
}
/// <summary>
/// Dynamic font style used by the label.
/// </summary>
public FontStyle fontStyle
{
get
{
return mFontStyle;
}
set
{
if (mFontStyle != value)
{
mFontStyle = value;
shouldBeProcessed = true;
ProcessAndRequest();
}
}
}
/// <summary>
/// Text alignment option.
/// </summary>
public Alignment alignment
{
get
{
return mAlignment;
}
set
{
if (mAlignment != value)
{
mAlignment = value;
shouldBeProcessed = true;
ProcessAndRequest();
}
}
}
/// <summary>
/// Whether a gradient will be applied.
/// </summary>
public bool applyGradient
{
get
{
return mApplyGradient;
}
set
{
if (mApplyGradient != value)
{
mApplyGradient = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Top gradient color.
/// </summary>
public Color gradientTop
{
get
{
return mGradientTop;
}
set
{
if (mGradientTop != value)
{
mGradientTop = value;
if (mApplyGradient) MarkAsChanged();
}
}
}
/// <summary>
/// Bottom gradient color.
/// </summary>
public Color gradientBottom
{
get
{
return mGradientBottom;
}
set
{
if (mGradientBottom != value)
{
mGradientBottom = value;
if (mApplyGradient) MarkAsChanged();
}
}
}
/// <summary>
/// Additional horizontal spacing between characters when printing text.
/// </summary>
public int spacingX
{
get
{
return mSpacingX;
}
set
{
if (mSpacingX != value)
{
mSpacingX = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Additional vertical spacing between lines when printing text.
/// </summary>
public int spacingY
{
get
{
return mSpacingY;
}
set
{
if (mSpacingY != value)
{
mSpacingY = value;
MarkAsChanged();
}
}
}
#if DYNAMIC_FONT
/// <summary>
/// Whether the label will use the printed size instead of font size when printing the label.
/// It's a dynamic font feature that will ensure that the text is crisp when shrunk.
/// </summary>
bool keepCrisp
{
get
{
if (trueTypeFont != null && keepCrispWhenShrunk != Crispness.Never)
{
#if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_BLACKBERRY
return (keepCrispWhenShrunk == Crispness.Always);
#else
return true;
#endif
}
return false;
}
}
#endif
/// <summary>
/// Whether this label will support color encoding in the format of [RRGGBB] and new line in the form of a "\\n" string.
/// </summary>
public bool supportEncoding
{
get
{
return mEncoding;
}
set
{
if (mEncoding != value)
{
mEncoding = value;
shouldBeProcessed = true;
}
}
}
/// <summary>
/// Style used for symbols.
/// </summary>
public NGUIText.SymbolStyle symbolStyle
{
get
{
return mSymbols;
}
set
{
if (mSymbols != value)
{
mSymbols = value;
shouldBeProcessed = true;
}
}
}
/// <summary>
/// Overflow method controls the label's behaviour when its content doesn't fit the bounds.
/// </summary>
public Overflow overflowMethod
{
get
{
return mOverflow;
}
set
{
if (mOverflow != value)
{
mOverflow = value;
shouldBeProcessed = true;
}
}
}
/// <summary>
/// Maximum width of the label in pixels.
/// </summary>
[System.Obsolete("Use 'width' instead")]
public int lineWidth
{
get { return width; }
set { width = value; }
}
/// <summary>
/// Maximum height of the label in pixels.
/// </summary>
[System.Obsolete("Use 'height' instead")]
public int lineHeight
{
get { return height; }
set { height = value; }
}
/// <summary>
/// Whether the label supports multiple lines.
/// </summary>
public bool multiLine
{
get
{
return mMaxLineCount != 1;
}
set
{
if ((mMaxLineCount != 1) != value)
{
mMaxLineCount = (value ? 0 : 1);
shouldBeProcessed = true;
}
}
}
/// <summary>
/// Process the label's text before returning its corners.
/// </summary>
public override Vector3[] localCorners
{
get
{
if (shouldBeProcessed) ProcessText();
return base.localCorners;
}
}
/// <summary>
/// Process the label's text before returning its corners.
/// </summary>
public override Vector3[] worldCorners
{
get
{
if (shouldBeProcessed) ProcessText();
return base.worldCorners;
}
}
/// <summary>
/// Process the label's text before returning its drawing dimensions.
/// </summary>
public override Vector4 drawingDimensions
{
get
{
if (shouldBeProcessed) ProcessText();
return base.drawingDimensions;
}
}
/// <summary>
/// The max number of lines to be displayed for the label
/// </summary>
public int maxLineCount
{
get
{
return mMaxLineCount;
}
set
{
if (mMaxLineCount != value)
{
mMaxLineCount = Mathf.Max(value, 0);
shouldBeProcessed = true;
if (overflowMethod == Overflow.ShrinkContent) MakePixelPerfect();
}
}
}
/// <summary>
/// What effect is used by the label.
/// </summary>
public Effect effectStyle
{
get
{
return mEffectStyle;
}
set
{
if (mEffectStyle != value)
{
mEffectStyle = value;
shouldBeProcessed = true;
}
}
}
/// <summary>
/// Color used by the effect, if it's enabled.
/// </summary>
public Color effectColor
{
get
{
return mEffectColor;
}
set
{
if (mEffectColor != value)
{
mEffectColor = value;
if (mEffectStyle != Effect.None) shouldBeProcessed = true;
}
}
}
/// <summary>
/// Effect distance in pixels.
/// </summary>
public Vector2 effectDistance
{
get
{
return mEffectDistance;
}
set
{
if (mEffectDistance != value)
{
mEffectDistance = value;
shouldBeProcessed = true;
}
}
}
/// <summary>
/// Whether the label will automatically shrink its size in order to fit the maximum line width.
/// </summary>
[System.Obsolete("Use 'overflowMethod == UILabel.Overflow.ShrinkContent' instead")]
public bool shrinkToFit
{
get
{
return mOverflow == Overflow.ShrinkContent;
}
set
{
if (value)
{
overflowMethod = Overflow.ShrinkContent;
}
}
}
/// <summary>
/// Returns the processed version of 'text', with new line characters, line wrapping, etc.
/// </summary>
public string processedText
{
get
{
if (mLastWidth != mWidth || mLastHeight != mHeight)
{
mLastWidth = mWidth;
mLastHeight = mHeight;
mShouldBeProcessed = true;
}
// Process the text if necessary
if (shouldBeProcessed) ProcessText();
return mProcessedText;
}
}
/// <summary>
/// Actual printed size of the text, in pixels.
/// </summary>
public Vector2 printedSize
{
get
{
if (shouldBeProcessed) ProcessText();
return mCalculatedSize;
}
}
/// <summary>
/// Local size of the widget, in pixels.
/// </summary>
public override Vector2 localSize
{
get
{
if (shouldBeProcessed) ProcessText();
return base.localSize;
}
}
/// <summary>
/// Whether the label has a valid font.
/// </summary>
#if DYNAMIC_FONT
bool isValid { get { return mFont != null || mTrueTypeFont != null; } }
#else
bool isValid { get { return mFont != null; } }
#endif
#if DYNAMIC_FONT
static BetterList<UILabel> mList = new BetterList<UILabel>();
static Dictionary<Font, int> mFontUsage = new Dictionary<Font, int>();
/// <summary>
/// Register the font texture change listener.
/// </summary>
protected override void OnInit ()
{
base.OnInit();
mList.Add(this);
SetActiveFont(trueTypeFont);
}
/// <summary>
/// Remove the font texture change listener.
/// </summary>
protected override void OnDisable ()
{
SetActiveFont(null);
mList.Remove(this);
base.OnDisable();
}
/// <summary>
/// Set the active font, correctly setting and clearing callbacks.
/// </summary>
protected void SetActiveFont (Font fnt)
{
if (mActiveTTF != fnt)
{
if (mActiveTTF != null)
{
int usage;
if (mFontUsage.TryGetValue(mActiveTTF, out usage))
{
usage = Mathf.Max(0, --usage);
if (usage == 0)
{
mActiveTTF.textureRebuildCallback = null;
mFontUsage.Remove(mActiveTTF);
}
else mFontUsage[mActiveTTF] = usage;
}
else mActiveTTF.textureRebuildCallback = null;
}
mActiveTTF = fnt;
if (mActiveTTF != null)
{
int usage = 0;
// Font hasn't been used yet? Register a change delegate callback
if (!mFontUsage.TryGetValue(mActiveTTF, out usage))
mActiveTTF.textureRebuildCallback = OnFontTextureChanged;
mFontUsage[mActiveTTF] = ++usage;
}
}
}
/// <summary>
/// Notification called when the Unity's font's texture gets rebuilt.
/// Unity's font has a nice tendency to simply discard other characters when the texture's dimensions change.
/// By requesting them inside the notification callback, we immediately force them back in.
/// Originally I was subscribing each label to the font individually, but as it turned out
/// mono's delegate system causes an insane amount of memory allocations when += or -= to a delegate.
/// So... queue yet another work-around.
/// </summary>
static void OnFontTextureChanged ()
{
for (int i = 0; i < mList.size; ++i)
{
UILabel lbl = mList[i];
if (lbl != null)
{
Font fnt = lbl.trueTypeFont;
if (fnt != null)
{
fnt.RequestCharactersInTexture(lbl.mText, lbl.mPrintedSize, lbl.mFontStyle);
lbl.MarkAsChanged();
}
}
}
}
#endif
/// <summary>
/// Get the sides of the rectangle relative to the specified transform.
/// The order is left, top, right, bottom.
/// </summary>
public override Vector3[] GetSides (Transform relativeTo)
{
if (shouldBeProcessed) ProcessText();
return base.GetSides(relativeTo);
}
/// <summary>
/// Upgrading labels is a bit different.
/// </summary>
protected override void UpgradeFrom265 ()
{
ProcessText(true, true);
if (mShrinkToFit)
{
overflowMethod = Overflow.ShrinkContent;
mMaxLineCount = 0;
}
if (mMaxLineWidth != 0)
{
width = mMaxLineWidth;
overflowMethod = mMaxLineCount > 0 ? Overflow.ResizeHeight : Overflow.ShrinkContent;
}
else overflowMethod = Overflow.ResizeFreely;
if (mMaxLineHeight != 0)
height = mMaxLineHeight;
if (mFont != null)
{
int min = mFont.defaultSize;
if (height < min) height = min;
}
mMaxLineWidth = 0;
mMaxLineHeight = 0;
mShrinkToFit = false;
if (GetComponent<BoxCollider>() != null)
NGUITools.AddWidgetCollider(gameObject, true);
}
/// <summary>
/// If the label is anchored it should not auto-resize.
/// </summary>
protected override void OnAnchor ()
{
if (mOverflow == Overflow.ResizeFreely)
{
if (isFullyAnchored)
mOverflow = Overflow.ShrinkContent;
}
else if (mOverflow == Overflow.ResizeHeight)
{
if (topAnchor.target != null && bottomAnchor.target != null)
mOverflow = Overflow.ShrinkContent;
}
base.OnAnchor();
}
/// <summary>
/// Request the needed characters in the texture.
/// </summary>
void ProcessAndRequest ()
{
#if UNITY_EDITOR
if (!NGUITools.GetActive(this)) return;
if (!mAllowProcessing) return;
#endif
if (ambigiousFont != null) ProcessText();
}
#if UNITY_EDITOR
// Used to ensure that we don't process font more than once inside OnValidate function below
bool mAllowProcessing = true;
bool mUsingTTF = true;
/// <summary>
/// Validate the properties.
/// </summary>
protected override void OnValidate ()
{
base.OnValidate();
if (NGUITools.GetActive(this))
{
Font ttf = mTrueTypeFont;
UIFont fnt = mFont;
// If the true type font was not used before, but now it is, clear the font reference
if (!mUsingTTF && ttf != null) fnt = null;
else if (mUsingTTF && fnt != null) ttf = null;
mFont = null;
mTrueTypeFont = null;
mAllowProcessing = false;
#if DYNAMIC_FONT
SetActiveFont(null);
#endif
if (fnt != null)
{
bitmapFont = fnt;
mUsingTTF = false;
}
else if (ttf != null)
{
trueTypeFont = ttf;
mUsingTTF = true;
}
shouldBeProcessed = true;
mAllowProcessing = true;
ProcessAndRequest();
if (autoResizeBoxCollider) ResizeCollider();
}
}
#endif
/// <summary>
/// Determine start-up values.
/// </summary>
protected override void OnStart ()
{
base.OnStart();
// Legacy support
if (mLineWidth > 0f)
{
mMaxLineWidth = Mathf.RoundToInt(mLineWidth);
mLineWidth = 0f;
}
if (!mMultiline)
{
mMaxLineCount = 1;
mMultiline = true;
}
// Whether this is a premultiplied alpha shader
mPremultiply = (material != null && material.shader != null && material.shader.name.Contains("Premultiplied"));
#if DYNAMIC_FONT
// Request the text within the font
ProcessAndRequest();
#endif
}
/// <summary>
/// UILabel needs additional processing when something changes.
/// </summary>
public override void MarkAsChanged ()
{
shouldBeProcessed = true;
base.MarkAsChanged();
}
/// <summary>
/// Process the raw text, called when something changes.
/// </summary>
void ProcessText () { ProcessText(false, true); }
/// <summary>
/// Process the raw text, called when something changes.
/// </summary>
void ProcessText (bool legacyMode, bool full)
{
if (!isValid) return;
mChanged = true;
shouldBeProcessed = false;
NGUIText.rectWidth = legacyMode ? (mMaxLineWidth != 0 ? mMaxLineWidth : 1000000) : width;
NGUIText.rectHeight = legacyMode ? (mMaxLineHeight != 0 ? mMaxLineHeight : 1000000) : height;
mPrintedSize = Mathf.Abs(legacyMode ? Mathf.RoundToInt(cachedTransform.localScale.x) : defaultFontSize);
mScale = 1f;
if (NGUIText.rectWidth < 1 || NGUIText.rectHeight < 0)
{
mProcessedText = "";
return;
}
#if DYNAMIC_FONT
bool isDynamic = (trueTypeFont != null);
if (isDynamic && keepCrisp)
{
UIRoot rt = root;
if (rt != null) mDensity = (rt != null) ? rt.pixelSizeAdjustment : 1f;
}
else mDensity = 1f;
#endif
if (full) UpdateNGUIText();
if (mOverflow == Overflow.ResizeFreely) NGUIText.rectWidth = 1000000;
if (mOverflow == Overflow.ResizeFreely || mOverflow == Overflow.ResizeHeight)
NGUIText.rectHeight = 1000000;
if (mPrintedSize > 0)
{
#if DYNAMIC_FONT
bool adjustSize = keepCrisp;
#endif
for (int ps = mPrintedSize; ps > 0; --ps)
{
#if DYNAMIC_FONT
// Adjust either the size, or the scale
if (adjustSize)
{
mPrintedSize = ps;
NGUIText.fontSize = mPrintedSize;
}
else
#endif
{
mScale = (float)ps / mPrintedSize;
#if DYNAMIC_FONT
NGUIText.fontScale = isDynamic ? mScale : ((float)mFontSize / mFont.defaultSize) * mScale;
#else
NGUIText.fontScale = ((float)mFontSize / mFont.defaultSize) * mScale;
#endif
}
NGUIText.Update(false);
// Wrap the text
bool fits = NGUIText.WrapText(mText, out mProcessedText, true);
if (mOverflow == Overflow.ShrinkContent && !fits)
{
if (--ps > 1) continue;
else break;
}
else if (mOverflow == Overflow.ResizeFreely)
{
mCalculatedSize = NGUIText.CalculatePrintedSize(mProcessedText);
mWidth = Mathf.Max(minWidth, Mathf.RoundToInt(mCalculatedSize.x));
mHeight = Mathf.Max(minHeight, Mathf.RoundToInt(mCalculatedSize.y));
if ((mWidth & 1) == 1) ++mWidth;
if ((mHeight & 1) == 1) ++mHeight;
}
else if (mOverflow == Overflow.ResizeHeight)
{
mCalculatedSize = NGUIText.CalculatePrintedSize(mProcessedText);
mHeight = Mathf.Max(minHeight, Mathf.RoundToInt(mCalculatedSize.y));
if ((mHeight & 1) == 1) ++mHeight;
}
else
{
mCalculatedSize = NGUIText.CalculatePrintedSize(mProcessedText);
}
// Upgrade to the new system
if (legacyMode)
{
width = Mathf.RoundToInt(mCalculatedSize.x);
height = Mathf.RoundToInt(mCalculatedSize.y);
cachedTransform.localScale = Vector3.one;
}
break;
}
}
else
{
cachedTransform.localScale = Vector3.one;
mProcessedText = "";
mScale = 1f;
}
}
/// <summary>
/// Text is pixel-perfect when its scale matches the size.
/// </summary>
public override void MakePixelPerfect ()
{
if (ambigiousFont != null)
{
Vector3 pos = cachedTransform.localPosition;
pos.x = Mathf.RoundToInt(pos.x);
pos.y = Mathf.RoundToInt(pos.y);
pos.z = Mathf.RoundToInt(pos.z);
cachedTransform.localPosition = pos;
cachedTransform.localScale = Vector3.one;
if (mOverflow == Overflow.ResizeFreely)
{
AssumeNaturalSize();
}
else
{
int w = width;
int h = height;
Overflow over = mOverflow;
if (over != Overflow.ResizeHeight) mWidth = 100000;
mHeight = 100000;
mOverflow = Overflow.ShrinkContent;
ProcessText(false, true);
mOverflow = over;
int minX = Mathf.RoundToInt(mCalculatedSize.x);
int minY = Mathf.RoundToInt(mCalculatedSize.y);
minX = Mathf.Max(minX, base.minWidth);
minY = Mathf.Max(minY, base.minHeight);
mWidth = Mathf.Max(w, minX);
mHeight = Mathf.Max(h, minY);
MarkAsChanged();
}
}
else base.MakePixelPerfect();
}
/// <summary>
/// Make the label assume its natural size.
/// </summary>
public void AssumeNaturalSize ()
{
if (ambigiousFont != null)
{
mWidth = 100000;
mHeight = 100000;
ProcessText(false, true);
mWidth = Mathf.RoundToInt(mCalculatedSize.x);
mHeight = Mathf.RoundToInt(mCalculatedSize.y);
if ((mWidth & 1) == 1) ++mWidth;
if ((mHeight & 1) == 1) ++mHeight;
MarkAsChanged();
}
}
[System.Obsolete("Use UILabel.GetCharacterAtPosition instead")]
public int GetCharacterIndex (Vector3 worldPos) { return GetCharacterIndexAtPosition(worldPos); }
[System.Obsolete("Use UILabel.GetCharacterAtPosition instead")]
public int GetCharacterIndex (Vector2 localPos) { return GetCharacterIndexAtPosition(localPos); }
static BetterList<Vector3> mTempVerts = new BetterList<Vector3>();
static BetterList<int> mTempIndices = new BetterList<int>();
/// <summary>
/// Return the index of the character at the specified world position.
/// </summary>
public int GetCharacterIndexAtPosition (Vector3 worldPos)
{
Vector2 localPos = cachedTransform.InverseTransformPoint(worldPos);
return GetCharacterIndexAtPosition(localPos);
}
/// <summary>
/// Return the index of the character at the specified local position.
/// </summary>
public int GetCharacterIndexAtPosition (Vector2 localPos)
{
if (isValid)
{
string text = processedText;
if (string.IsNullOrEmpty(text)) return 0;
UpdateNGUIText();
NGUIText.PrintCharacterPositions(text, mTempVerts, mTempIndices);
if (mTempVerts.size > 0)
{
ApplyOffset(mTempVerts, 0);
int retVal = NGUIText.GetClosestCharacter(mTempVerts, localPos);
retVal = mTempIndices[retVal];
mTempVerts.Clear();
mTempIndices.Clear();
return retVal;
}
}
return 0;
}
/// <summary>
/// Retrieve the word directly below the specified world-space position.
/// </summary>
public string GetWordAtPosition (Vector3 worldPos) { return GetWordAtCharacterIndex(GetCharacterIndexAtPosition(worldPos)); }
/// <summary>
/// Retrieve the word directly below the specified relative-to-label position.
/// </summary>
public string GetWordAtPosition (Vector2 localPos) { return GetWordAtCharacterIndex(GetCharacterIndexAtPosition(localPos)); }
/// <summary>
/// Retrieve the word right under the specified character index.
/// </summary>
public string GetWordAtCharacterIndex (int characterIndex)
{
if (characterIndex != -1 && characterIndex < mText.Length)
{
int linkStart = mText.LastIndexOf(' ', characterIndex) + 1;
int linkEnd = mText.IndexOf(' ', characterIndex);
if (linkEnd == -1) linkEnd = mText.Length;
if (linkStart != linkEnd)
{
int len = linkEnd - linkStart;
if (len > 0)
{
string word = mText.Substring(linkStart, len);
return NGUIText.StripSymbols(word);
}
}
}
return null;
}
/// <summary>
/// Retrieve the URL directly below the specified world-space position.
/// </summary>
public string GetUrlAtPosition (Vector3 worldPos) { return GetUrlAtCharacterIndex(GetCharacterIndexAtPosition(worldPos)); }
/// <summary>
/// Retrieve the URL directly below the specified relative-to-label position.
/// </summary>
public string GetUrlAtPosition (Vector2 localPos) { return GetUrlAtCharacterIndex(GetCharacterIndexAtPosition(localPos)); }
/// <summary>
/// Retrieve the URL right under the specified character index.
/// </summary>
public string GetUrlAtCharacterIndex (int characterIndex)
{
if (characterIndex != -1 && characterIndex < mText.Length)
{
int linkStart = mText.LastIndexOf("[url=", characterIndex);
if (linkStart != -1)
{
linkStart += 5;
int linkEnd = mText.IndexOf("]", linkStart);
if (linkEnd != -1)
{
int closingStatement = mText.IndexOf("[/url]", linkEnd);
if (closingStatement == -1 || closingStatement >= characterIndex)
return mText.Substring(linkStart, linkEnd - linkStart);
}
}
}
return null;
}
/// <summary>
/// Get the index of the character on the line directly above or below the current index.
/// </summary>
public int GetCharacterIndex (int currentIndex, KeyCode key)
{
if (isValid)
{
string text = processedText;
if (string.IsNullOrEmpty(text)) return 0;
int def = defaultFontSize;
UpdateNGUIText();
NGUIText.PrintCharacterPositions(text, mTempVerts, mTempIndices);
if (mTempVerts.size > 0)
{
ApplyOffset(mTempVerts, 0);
for (int i = 0; i < mTempIndices.size; ++i)
{
if (mTempIndices[i] == currentIndex)
{
// Determine position on the line above or below this character
Vector2 localPos = mTempVerts[i];
if (key == KeyCode.UpArrow) localPos.y += def + spacingY;
else if (key == KeyCode.DownArrow) localPos.y -= def + spacingY;
else if (key == KeyCode.Home) localPos.x -= 1000f;
else if (key == KeyCode.End) localPos.x += 1000f;
// Find the closest character to this position
int retVal = NGUIText.GetClosestCharacter(mTempVerts, localPos);
retVal = mTempIndices[retVal];
if (retVal == currentIndex) break;
mTempVerts.Clear();
mTempIndices.Clear();
return retVal;
}
}
mTempVerts.Clear();
mTempIndices.Clear();
}
// If the selection doesn't move, then we're at the top or bottom-most line
if (key == KeyCode.UpArrow || key == KeyCode.Home) return 0;
if (key == KeyCode.DownArrow || key == KeyCode.End) return text.Length;
}
return currentIndex;
}
/// <summary>
/// Fill the specified geometry buffer with vertices that would highlight the current selection.
/// </summary>
public void PrintOverlay (int start, int end, UIGeometry caret, UIGeometry highlight, Color caretColor, Color highlightColor)
{
if (caret != null) caret.Clear();
if (highlight != null) highlight.Clear();
if (!isValid) return;
string text = processedText;
UpdateNGUIText();
int startingCaretVerts = caret.verts.size;
Vector2 center = new Vector2(0.5f, 0.5f);
float alpha = finalAlpha;
// If we have a highlight to work with, fill the buffer
if (highlight != null && start != end)
{
int startingVertices = highlight.verts.size;
NGUIText.PrintCaretAndSelection(text, start, end, caret.verts, highlight.verts);
if (highlight.verts.size > startingVertices)
{
ApplyOffset(highlight.verts, startingVertices);
Color32 c = new Color(highlightColor.r, highlightColor.g, highlightColor.b, highlightColor.a * alpha);
for (int i = startingVertices; i < highlight.verts.size; ++i)
{
highlight.uvs.Add(center);
highlight.cols.Add(c);
}
}
}
else NGUIText.PrintCaretAndSelection(text, start, end, caret.verts, null);
// Fill the caret UVs and colors
ApplyOffset(caret.verts, startingCaretVerts);
Color32 cc = new Color(caretColor.r, caretColor.g, caretColor.b, caretColor.a * alpha);
for (int i = startingCaretVerts; i < caret.verts.size; ++i)
{
caret.uvs.Add(center);
caret.cols.Add(cc);
}
}
/// <summary>
/// Draw the label.
/// </summary>
public override void OnFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (!isValid) return;
int offset = verts.size;
Color col = color;
col.a = finalAlpha;
if (mFont != null && mFont.premultipliedAlphaShader) col = NGUITools.ApplyPMA(col);
string text = processedText;
int start = verts.size;
UpdateNGUIText();
NGUIText.tint = col;
NGUIText.Print(text, verts, uvs, cols);
// Center the content within the label vertically
Vector2 pos = ApplyOffset(verts, start);
// Effects don't work with packed fonts
if (mFont != null && mFont.packedFontShader) return;
// Apply an effect if one was requested
if (effectStyle != Effect.None)
{
int end = verts.size;
pos.x = mEffectDistance.x;
pos.y = mEffectDistance.y;
ApplyShadow(verts, uvs, cols, offset, end, pos.x, -pos.y);
if (effectStyle == Effect.Outline)
{
offset = end;
end = verts.size;
ApplyShadow(verts, uvs, cols, offset, end, -pos.x, pos.y);
offset = end;
end = verts.size;
ApplyShadow(verts, uvs, cols, offset, end, pos.x, pos.y);
offset = end;
end = verts.size;
ApplyShadow(verts, uvs, cols, offset, end, -pos.x, -pos.y);
}
}
}
/// <summary>
/// Align the vertices, making the label positioned correctly based on the pivot.
/// Returns the offset that was applied.
/// </summary>
protected Vector2 ApplyOffset (BetterList<Vector3> verts, int start)
{
Vector2 po = pivotOffset;
float fx = Mathf.Lerp(0f, -mWidth, po.x);
float fy = Mathf.Lerp(mHeight, 0f, po.y) + Mathf.Lerp((mCalculatedSize.y - mHeight), 0f, po.y);
fx = Mathf.Round(fx);
fy = Mathf.Round(fy);
#if UNITY_FLASH
for (int i = start; i < verts.size; ++i)
{
Vector3 buff = verts.buffer[i];
buff.x += fx;
buff.y += fy;
verts.buffer[i] = buff;
}
#else
for (int i = start; i < verts.size; ++i)
{
verts.buffer[i].x += fx;
verts.buffer[i].y += fy;
}
#endif
return new Vector2(fx, fy);
}
/// <summary>
/// Apply a shadow effect to the buffer.
/// </summary>
void ApplyShadow (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, int start, int end, float x, float y)
{
Color c = mEffectColor;
c.a *= finalAlpha;
Color32 col = (bitmapFont != null && bitmapFont.premultipliedAlphaShader) ? NGUITools.ApplyPMA(c) : c;
for (int i = start; i < end; ++i)
{
verts.Add(verts.buffer[i]);
uvs.Add(uvs.buffer[i]);
cols.Add(cols.buffer[i]);
Vector3 v = verts.buffer[i];
v.x += x;
v.y += y;
verts.buffer[i] = v;
cols.buffer[i] = col;
}
}
/// <summary>
/// Calculate the character index offset necessary in order to print the end of the specified text.
/// </summary>
public int CalculateOffsetToFit (string text)
{
UpdateNGUIText();
NGUIText.encoding = false;
NGUIText.symbolStyle = NGUIText.SymbolStyle.None;
return NGUIText.CalculateOffsetToFit(text);
}
/// <summary>
/// Convenience function, in case you wanted to associate progress bar, slider or scroll bar's
/// OnValueChanged function in inspector with a label.
/// </summary>
public void SetCurrentProgress ()
{
if (UIProgressBar.current != null)
text = UIProgressBar.current.value.ToString("F");
}
/// <summary>
/// Convenience function, in case you wanted to associate progress bar, slider or scroll bar's
/// OnValueChanged function in inspector with a label.
/// </summary>
public void SetCurrentPercent ()
{
if (UIProgressBar.current != null)
text = Mathf.RoundToInt(UIProgressBar.current.value * 100f) + "%";
}
/// <summary>
/// Convenience function, in case you wanted to automatically set some label's text
/// by selecting a value in the UIPopupList.
/// </summary>
public void SetCurrentSelection ()
{
if (UIPopupList.current != null)
{
text = UIPopupList.current.isLocalized ?
Localization.Get(UIPopupList.current.value) :
UIPopupList.current.value;
}
}
/// <summary>
/// Convenience function -- wrap the current text given the label's settings and unlimited height.
/// </summary>
public bool Wrap (string text, out string final) { return Wrap(text, out final, 1000000); }
/// <summary>
/// Convenience function -- wrap the current text given the label's settings and the given height.
/// </summary>
public bool Wrap (string text, out string final, int height)
{
UpdateNGUIText();
return NGUIText.WrapText(text, out final);
}
/// <summary>
/// Update NGUIText.current with all the properties from this label.
/// </summary>
public void UpdateNGUIText ()
{
Font ttf = trueTypeFont;
bool isDynamic = (ttf != null);
NGUIText.fontSize = mPrintedSize;
NGUIText.fontStyle = mFontStyle;
NGUIText.rectWidth = mWidth;
NGUIText.rectHeight = mHeight;
NGUIText.gradient = mApplyGradient && (mFont == null || !mFont.packedFontShader);
NGUIText.gradientTop = mGradientTop;
NGUIText.gradientBottom = mGradientBottom;
NGUIText.encoding = mEncoding;
NGUIText.premultiply = mPremultiply;
NGUIText.symbolStyle = mSymbols;
NGUIText.maxLines = mMaxLineCount;
NGUIText.spacingX = mSpacingX;
NGUIText.spacingY = mSpacingY;
NGUIText.fontScale = isDynamic ? mScale : ((float)mFontSize / mFont.defaultSize) * mScale;
if (mFont != null)
{
NGUIText.bitmapFont = mFont;
for (; ; )
{
UIFont fnt = NGUIText.bitmapFont.replacement;
if (fnt == null) break;
NGUIText.bitmapFont = fnt;
}
#if DYNAMIC_FONT
if (NGUIText.bitmapFont.isDynamic)
{
NGUIText.dynamicFont = NGUIText.bitmapFont.dynamicFont;
NGUIText.bitmapFont = null;
}
else NGUIText.dynamicFont = null;
#endif
}
#if DYNAMIC_FONT
else
{
NGUIText.dynamicFont = ttf;
NGUIText.bitmapFont = null;
}
if (isDynamic && keepCrisp)
{
UIRoot rt = root;
if (rt != null) NGUIText.pixelDensity = (rt != null) ? rt.pixelSizeAdjustment : 1f;
}
else NGUIText.pixelDensity = 1f;
if (mDensity != NGUIText.pixelDensity)
{
ProcessText(false, false);
NGUIText.rectWidth = mWidth;
NGUIText.rectHeight = mHeight;
}
#endif
if (alignment == Alignment.Automatic)
{
Pivot p = pivot;
if (p == Pivot.Left || p == Pivot.TopLeft || p == Pivot.BottomLeft)
{
NGUIText.alignment = Alignment.Left;
}
else if (p == Pivot.Right || p == Pivot.TopRight || p == Pivot.BottomRight)
{
NGUIText.alignment = Alignment.Right;
}
else NGUIText.alignment = Alignment.Center;
}
else NGUIText.alignment = alignment;
NGUIText.Update();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UILabel.cs
|
C#
|
asf20
| 37,049
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if UNITY_FLASH || UNITY_WP8 || UNITY_METRO
#define USE_SIMPLE_DICTIONARY
#endif
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// UI Panel is responsible for collecting, sorting and updating widgets in addition to generating widgets' geometry.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/NGUI Panel")]
public class UIPanel : UIRect
{
/// <summary>
/// List of active panels.
/// </summary>
static public BetterList<UIPanel> list = new BetterList<UIPanel>();
public enum RenderQueue
{
Automatic,
StartAt,
Explicit,
}
public delegate void OnGeometryUpdated ();
/// <summary>
/// Notification triggered when the panel's geometry get rebuilt. It's mainly here for debugging purposes.
/// </summary>
public OnGeometryUpdated onGeometryUpdated;
/// <summary>
/// Whether this panel will show up in the panel tool (set this to 'false' for dynamically created temporary panels)
/// </summary>
public bool showInPanelTool = true;
/// <summary>
/// Whether normals and tangents will be generated for all meshes
/// </summary>
public bool generateNormals = false;
/// <summary>
/// Whether widgets drawn by this panel are static (won't move). This will improve performance.
/// </summary>
public bool widgetsAreStatic = false;
/// <summary>
/// Whether widgets will be culled while the panel is being dragged.
/// Having this on improves performance, but turning it off will reduce garbage collection.
/// </summary>
public bool cullWhileDragging = false;
/// <summary>
/// Optimization flag. Makes the assumption that the panel's geometry
/// will always be on screen and the bounds don't need to be re-calculated.
/// </summary>
public bool alwaysOnScreen = false;
/// <summary>
/// By default, non-clipped panels use the camera's bounds, and the panel's position has no effect.
/// If you want the panel's position to actually be used with anchors, set this field to 'true'.
/// </summary>
public bool anchorOffset = false;
/// <summary>
/// By default all panels manage render queues of their draw calls themselves by incrementing them
/// so that the geometry is drawn in the proper order. You can alter this behaviour.
/// </summary>
public RenderQueue renderQueue = RenderQueue.Automatic;
/// <summary>
/// Render queue used by the panel. The default value of '3000' is the equivalent of "Transparent".
/// This property is only used if 'renderQueue' is set to something other than "Automatic".
/// </summary>
public int startingRenderQueue = 3000;
/// <summary>
/// List of widgets managed by this panel. Do not attempt to modify this list yourself.
/// </summary>
[System.NonSerialized]
public BetterList<UIWidget> widgets = new BetterList<UIWidget>();
/// <summary>
/// List of draw calls created by this panel. Do not attempt to modify this list yourself.
/// </summary>
[System.NonSerialized]
public BetterList<UIDrawCall> drawCalls = new BetterList<UIDrawCall>();
/// <summary>
/// Matrix that will transform the specified world coordinates to relative-to-panel coordinates.
/// </summary>
[System.NonSerialized]
public Matrix4x4 worldToLocal = Matrix4x4.identity;
/// <summary>
/// Cached clip range passed to the draw call's shader.
/// </summary>
[System.NonSerialized]
public Vector4 drawCallClipRange = new Vector4(0f, 0f, 1f, 1f);
public delegate void OnClippingMoved (UIPanel panel);
/// <summary>
/// Event callback that's triggered when the panel's clip region gets moved.
/// </summary>
public OnClippingMoved onClipMove;
// Panel's alpha (affects the alpha of all widgets)
[HideInInspector][SerializeField] float mAlpha = 1f;
// Clipping rectangle
[HideInInspector][SerializeField] UIDrawCall.Clipping mClipping = UIDrawCall.Clipping.None;
[HideInInspector][SerializeField] Vector4 mClipRange = new Vector4(0f, 0f, 300f, 200f);
[HideInInspector][SerializeField] Vector2 mClipSoftness = new Vector2(4f, 4f);
[HideInInspector][SerializeField] int mDepth = 0;
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
[HideInInspector][SerializeField] int mSortingOrder = 0;
#endif
// Whether a full rebuild of geometry buffers is required
bool mRebuild = false;
bool mResized = false;
Camera mCam;
[SerializeField] Vector2 mClipOffset = Vector2.zero;
float mCullTime = 0f;
float mUpdateTime = 0f;
int mMatrixFrame = -1;
int mAlphaFrameID = 0;
int mLayer = -1;
// Values used for visibility checks
static float[] mTemp = new float[4];
Vector2 mMin = Vector2.zero;
Vector2 mMax = Vector2.zero;
bool mHalfPixelOffset = false;
bool mSortWidgets = false;
/// <summary>
/// Helper property that returns the first unused depth value.
/// </summary>
static public int nextUnusedDepth
{
get
{
int highest = int.MinValue;
for (int i = 0; i < list.size; ++i)
highest = Mathf.Max(highest, list[i].depth);
return (highest == int.MinValue) ? 0 : highest + 1;
}
}
/// <summary>
/// Whether the rectangle can be anchored.
/// </summary>
public override bool canBeAnchored { get { return mClipping != UIDrawCall.Clipping.None; } }
/// <summary>
/// Panel's alpha affects everything drawn by the panel.
/// </summary>
public override float alpha
{
get
{
return mAlpha;
}
set
{
float val = Mathf.Clamp01(value);
if (mAlpha != val)
{
mAlphaFrameID = -1;
mResized = true;
mAlpha = val;
SetDirty();
}
}
}
/// <summary>
/// Panels can have their own depth value that will change the order with which everything they manage gets drawn.
/// </summary>
public int depth
{
get
{
return mDepth;
}
set
{
if (mDepth != value)
{
mDepth = value;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
list.Sort(CompareFunc);
}
}
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
/// <summary>
/// Sorting order value for the panel's draw calls, to be used with Unity's 2D system.
/// </summary>
public int sortingOrder
{
get
{
return mSortingOrder;
}
set
{
if (mSortingOrder != value)
{
mSortingOrder = value;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
UpdateDrawCalls();
}
}
}
#endif
/// <summary>
/// Function that can be used to depth-sort panels.
/// </summary>
static public int CompareFunc (UIPanel a, UIPanel b)
{
if (a != b && a != null && b != null)
{
if (a.mDepth < b.mDepth) return -1;
if (a.mDepth > b.mDepth) return 1;
return (a.GetInstanceID() < b.GetInstanceID()) ? -1 : 1;
}
return 0;
}
/// <summary>
/// Panel's width in pixels.
/// </summary>
public float width { get { return GetViewSize().x; } }
/// <summary>
/// Panel's height in pixels.
/// </summary>
public float height { get { return GetViewSize().y; } }
/// <summary>
/// Whether the panel's drawn geometry needs to be offset by a half-pixel.
/// </summary>
public bool halfPixelOffset { get { return mHalfPixelOffset; } }
/// <summary>
/// Whether the camera is used to draw UI geometry.
/// </summary>
public bool usedForUI { get { return (mCam != null && mCam.isOrthoGraphic); } }
/// <summary>
/// Directx9 pixel offset, used for drawing.
/// </summary>
public Vector3 drawCallOffset
{
get
{
if (mHalfPixelOffset && mCam != null && mCam.isOrthoGraphic)
{
Vector2 size = GetWindowSize();
float mod = (1f / size.y) / mCam.orthographicSize;
return new Vector3(-mod, mod);
}
return Vector3.zero;
}
}
/// <summary>
/// Clipping method used by all draw calls.
/// </summary>
public UIDrawCall.Clipping clipping
{
get
{
return mClipping;
}
set
{
if (mClipping != value)
{
mResized = true;
mClipping = value;
mMatrixFrame = -1;
#if UNITY_EDITOR
if (!Application.isPlaying) UpdateDrawCalls();
#endif
}
}
}
UIPanel mParentPanel = null;
/// <summary>
/// Reference to the parent panel, if any.
/// </summary>
public UIPanel parentPanel { get { return mParentPanel; } }
/// <summary>
/// Number of times the panel's contents get clipped.
/// </summary>
public int clipCount
{
get
{
int count = 0;
UIPanel p = this;
while (p != null)
{
if (p.mClipping == UIDrawCall.Clipping.SoftClip) ++count;
p = p.mParentPanel;
}
return count;
}
}
/// <summary>
/// Whether the panel will actually perform clipping of children.
/// </summary>
public bool hasClipping { get { return mClipping == UIDrawCall.Clipping.SoftClip; } }
/// <summary>
/// Whether the panel will actually perform clipping of children.
/// </summary>
public bool hasCumulativeClipping { get { return clipCount != 0; } }
[System.Obsolete("Use 'hasClipping' or 'hasCumulativeClipping' instead")]
public bool clipsChildren { get { return hasCumulativeClipping; } }
/// <summary>
/// Clipping area offset used to make it possible to move clipped panels (scroll views) efficiently.
/// Scroll views move by adjusting the clip offset by one value, and the transform position by the inverse.
/// This makes it possible to not have to rebuild the geometry, greatly improving performance.
/// </summary>
public Vector2 clipOffset
{
get
{
return mClipOffset;
}
set
{
if (Mathf.Abs(mClipOffset.x - value.x) > 0.001f ||
Mathf.Abs(mClipOffset.y - value.y) > 0.001f)
{
mResized = true;
mCullTime = (mCullTime == 0f) ? 0.001f : RealTime.time + 0.15f;
mClipOffset = value;
mMatrixFrame = -1;
// Call the event delegate
if (onClipMove != null) onClipMove(this);
#if UNITY_EDITOR
if (!Application.isPlaying) UpdateDrawCalls();
#endif
}
}
}
/// <summary>
/// Clipping position (XY) and size (ZW).
/// Note that you should not be modifying this property at run-time to reposition the clipping. Adjust clipOffset instead.
/// </summary>
[System.Obsolete("Use 'finalClipRegion' or 'baseClipRegion' instead")]
public Vector4 clipRange
{
get
{
return baseClipRegion;
}
set
{
baseClipRegion = value;
}
}
/// <summary>
/// Clipping position (XY) and size (ZW).
/// Note that you should not be modifying this property at run-time to reposition the clipping. Adjust clipOffset instead.
/// </summary>
public Vector4 baseClipRegion
{
get
{
return mClipRange;
}
set
{
if (Mathf.Abs(mClipRange.x - value.x) > 0.001f ||
Mathf.Abs(mClipRange.y - value.y) > 0.001f ||
Mathf.Abs(mClipRange.z - value.z) > 0.001f ||
Mathf.Abs(mClipRange.w - value.w) > 0.001f)
{
mResized = true;
mCullTime = (mCullTime == 0f) ? 0.001f : RealTime.time + 0.15f;
mClipRange = value;
mMatrixFrame = -1;
UIScrollView sv = GetComponent<UIScrollView>();
if (sv != null) sv.UpdatePosition();
if (onClipMove != null) onClipMove(this);
#if UNITY_EDITOR
if (!Application.isPlaying) UpdateDrawCalls();
#endif
}
}
}
/// <summary>
/// Final clipping region after the offset has been taken into consideration. XY = center, ZW = size.
/// </summary>
public Vector4 finalClipRegion
{
get
{
Vector2 size = GetViewSize();
if (mClipping != UIDrawCall.Clipping.None)
{
return new Vector4(mClipRange.x + mClipOffset.x, mClipRange.y + mClipOffset.y, size.x, size.y);
}
return new Vector4(0f, 0f, size.x, size.y);
}
}
/// <summary>
/// Clipping softness is used if the clipped style is set to "Soft".
/// </summary>
public Vector2 clipSoftness
{
get
{
return mClipSoftness;
}
set
{
if (mClipSoftness != value)
{
mClipSoftness = value;
#if UNITY_EDITOR
if (!Application.isPlaying) UpdateDrawCalls();
#endif
}
}
}
// Temporary variable to avoid GC allocation
static Vector3[] mCorners = new Vector3[4];
/// <summary>
/// Local-space corners of the panel's clipping rectangle. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
public override Vector3[] localCorners
{
get
{
if (mClipping == UIDrawCall.Clipping.None)
{
Vector2 size = GetViewSize();
float x0 = -0.5f * size.x;
float y0 = -0.5f * size.y;
float x1 = x0 + size.x;
float y1 = y0 + size.y;
Transform wt = (mCam != null) ? mCam.transform : null;
if (wt != null)
{
mCorners[0] = wt.TransformPoint(x0, y0, 0f);
mCorners[1] = wt.TransformPoint(x0, y1, 0f);
mCorners[2] = wt.TransformPoint(x1, y1, 0f);
mCorners[3] = wt.TransformPoint(x1, y0, 0f);
wt = cachedTransform;
for (int i = 0; i < 4; ++i)
mCorners[i] = wt.InverseTransformPoint(mCorners[i]);
}
else
{
mCorners[0] = new Vector3(x0, y0);
mCorners[1] = new Vector3(x0, y1);
mCorners[2] = new Vector3(x1, y1);
mCorners[3] = new Vector3(x1, y0);
}
}
else
{
float x0 = mClipOffset.x + mClipRange.x - 0.5f * mClipRange.z;
float y0 = mClipOffset.y + mClipRange.y - 0.5f * mClipRange.w;
float x1 = x0 + mClipRange.z;
float y1 = y0 + mClipRange.w;
mCorners[0] = new Vector3(x0, y0);
mCorners[1] = new Vector3(x0, y1);
mCorners[2] = new Vector3(x1, y1);
mCorners[3] = new Vector3(x1, y0);
}
return mCorners;
}
}
/// <summary>
/// World-space corners of the panel's clipping rectangle. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
public override Vector3[] worldCorners
{
get
{
if (mClipping == UIDrawCall.Clipping.None)
{
Vector2 size = GetViewSize();
float x0 = -0.5f * size.x;
float y0 = -0.5f * size.y;
float x1 = x0 + size.x;
float y1 = y0 + size.y;
Transform wt = (mCam != null) ? mCam.transform : null;
if (wt != null)
{
mCorners[0] = wt.TransformPoint(x0, y0, 0f);
mCorners[1] = wt.TransformPoint(x0, y1, 0f);
mCorners[2] = wt.TransformPoint(x1, y1, 0f);
mCorners[3] = wt.TransformPoint(x1, y0, 0f);
}
}
else
{
float x0 = mClipOffset.x + mClipRange.x - 0.5f * mClipRange.z;
float y0 = mClipOffset.y + mClipRange.y - 0.5f * mClipRange.w;
float x1 = x0 + mClipRange.z;
float y1 = y0 + mClipRange.w;
Transform wt = cachedTransform;
mCorners[0] = wt.TransformPoint(x0, y0, 0f);
mCorners[1] = wt.TransformPoint(x0, y1, 0f);
mCorners[2] = wt.TransformPoint(x1, y1, 0f);
mCorners[3] = wt.TransformPoint(x1, y0, 0f);
}
return mCorners;
}
}
/// <summary>
/// Get the sides of the rectangle relative to the specified transform.
/// The order is left, top, right, bottom.
/// </summary>
public override Vector3[] GetSides (Transform relativeTo)
{
if (mClipping != UIDrawCall.Clipping.None || anchorOffset)
{
Vector2 size = GetViewSize();
Vector2 cr = (mClipping != UIDrawCall.Clipping.None) ? (Vector2)mClipRange + mClipOffset : Vector2.zero;
float x0 = cr.x - 0.5f * size.x;
float y0 = cr.y - 0.5f * size.y;
float x1 = x0 + size.x;
float y1 = y0 + size.y;
float cx = (x0 + x1) * 0.5f;
float cy = (y0 + y1) * 0.5f;
Matrix4x4 mat = cachedTransform.localToWorldMatrix;
mCorners[0] = mat.MultiplyPoint3x4(new Vector3(x0, cy));
mCorners[1] = mat.MultiplyPoint3x4(new Vector3(cx, y1));
mCorners[2] = mat.MultiplyPoint3x4(new Vector3(x1, cy));
mCorners[3] = mat.MultiplyPoint3x4(new Vector3(cx, y0));
if (relativeTo != null)
{
for (int i = 0; i < 4; ++i)
mCorners[i] = relativeTo.InverseTransformPoint(mCorners[i]);
}
return mCorners;
}
return base.GetSides(relativeTo);
}
/// <summary>
/// Invalidating the panel should reset its alpha.
/// </summary>
public override void Invalidate (bool includeChildren)
{
mAlphaFrameID = -1;
base.Invalidate(includeChildren);
}
/// <summary>
/// Widget's final alpha, after taking the panel's alpha into account.
/// </summary>
public override float CalculateFinalAlpha (int frameID)
{
if (mAlphaFrameID != frameID)
{
mAlphaFrameID = frameID;
UIRect pt = parent;
finalAlpha = (parent != null) ? pt.CalculateFinalAlpha(frameID) * mAlpha : mAlpha;
}
return finalAlpha;
}
/// <summary>
/// Set the panel's rectangle.
/// </summary>
public override void SetRect (float x, float y, float width, float height)
{
int finalWidth = Mathf.FloorToInt(width + 0.5f);
int finalHeight = Mathf.FloorToInt(height + 0.5f);
finalWidth = ((finalWidth >> 1) << 1);
finalHeight = ((finalHeight >> 1) << 1);
Transform t = cachedTransform;
Vector3 pos = t.localPosition;
pos.x = Mathf.Floor(x + 0.5f);
pos.y = Mathf.Floor(y + 0.5f);
if (finalWidth < 2) finalWidth = 2;
if (finalHeight < 2) finalHeight = 2;
baseClipRegion = new Vector4(pos.x, pos.y, finalWidth, finalHeight);
if (isAnchored)
{
t = t.parent;
if (leftAnchor.target) leftAnchor.SetHorizontal(t, x);
if (rightAnchor.target) rightAnchor.SetHorizontal(t, x + width);
if (bottomAnchor.target) bottomAnchor.SetVertical(t, y);
if (topAnchor.target) topAnchor.SetVertical(t, y + height);
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
}
/// <summary>
/// Returns whether the specified rectangle is visible by the panel. The coordinates must be in world space.
/// </summary>
public bool IsVisible (Vector3 a, Vector3 b, Vector3 c, Vector3 d)
{
UpdateTransformMatrix();
// Transform the specified points from world space to local space
a = worldToLocal.MultiplyPoint3x4(a);
b = worldToLocal.MultiplyPoint3x4(b);
c = worldToLocal.MultiplyPoint3x4(c);
d = worldToLocal.MultiplyPoint3x4(d);
mTemp[0] = a.x;
mTemp[1] = b.x;
mTemp[2] = c.x;
mTemp[3] = d.x;
float minX = Mathf.Min(mTemp);
float maxX = Mathf.Max(mTemp);
mTemp[0] = a.y;
mTemp[1] = b.y;
mTemp[2] = c.y;
mTemp[3] = d.y;
float minY = Mathf.Min(mTemp);
float maxY = Mathf.Max(mTemp);
if (maxX < mMin.x) return false;
if (maxY < mMin.y) return false;
if (minX > mMax.x) return false;
if (minY > mMax.y) return false;
return true;
}
/// <summary>
/// Returns whether the specified world position is within the panel's bounds determined by the clipping rect.
/// </summary>
public bool IsVisible (Vector3 worldPos)
{
if (mAlpha < 0.001f) return false;
if (mClipping == UIDrawCall.Clipping.None ||
mClipping == UIDrawCall.Clipping.ConstrainButDontClip) return true;
UpdateTransformMatrix();
Vector3 pos = worldToLocal.MultiplyPoint3x4(worldPos);
if (pos.x < mMin.x) return false;
if (pos.y < mMin.y) return false;
if (pos.x > mMax.x) return false;
if (pos.y > mMax.y) return false;
return true;
}
/// <summary>
/// Returns whether the specified widget is visible by the panel.
/// </summary>
public bool IsVisible (UIWidget w)
{
if ((mClipping == UIDrawCall.Clipping.None || mClipping == UIDrawCall.Clipping.ConstrainButDontClip) && !w.hideIfOffScreen)
{
if (mParentPanel == null || clipCount == 0) return true;
}
UIPanel p = this;
Vector3[] corners = w.worldCorners;
while (p != null)
{
if (!IsVisible(corners[0], corners[1], corners[2], corners[3])) return false;
p = p.mParentPanel;
}
return true;
}
/// <summary>
/// Whether the specified widget is going to be affected by this panel in any way.
/// </summary>
public bool Affects (UIWidget w)
{
if (w == null) return false;
UIPanel expected = w.panel;
if (expected == null) return false;
UIPanel p = this;
while (p != null)
{
if (p == expected) return true;
if (!p.hasCumulativeClipping) return false;
p = p.mParentPanel;
}
return false;
}
/// <summary>
/// Causes all draw calls to be re-created on the next update.
/// </summary>
[ContextMenu("Force Refresh")]
public void RebuildAllDrawCalls () { mRebuild = true; }
/// <summary>
/// Invalidate the panel's draw calls, forcing them to be rebuilt on the next update.
/// This call also affects all children.
/// </summary>
public void SetDirty ()
{
for (int i = 0; i < drawCalls.size; ++i)
drawCalls.buffer[i].isDirty = true;
Invalidate(true);
}
/// <summary>
/// Cache components.
/// </summary>
void Awake ()
{
mGo = gameObject;
mTrans = transform;
mHalfPixelOffset = (Application.platform == RuntimePlatform.WindowsPlayer ||
Application.platform == RuntimePlatform.XBOX360 ||
Application.platform == RuntimePlatform.WindowsWebPlayer ||
Application.platform == RuntimePlatform.WindowsEditor);
// Only DirectX 9 needs the half-pixel offset
if (mHalfPixelOffset) mHalfPixelOffset = (SystemInfo.graphicsShaderLevel < 40);
}
/// <summary>
/// Remember the parent panel, if any.
/// </summary>
protected override void OnEnable ()
{
base.OnEnable();
Transform parent = cachedTransform.parent;
mParentPanel = (parent != null) ? NGUITools.FindInParents<UIPanel>(parent.gameObject) : null;
}
/// <summary>
/// Find the parent panel, if we have one.
/// </summary>
public override void ParentHasChanged ()
{
base.ParentHasChanged();
Transform parent = cachedTransform.parent;
mParentPanel = (parent != null) ? NGUITools.FindInParents<UIPanel>(parent.gameObject) : null;
}
/// <summary>
/// Layer is used to ensure that if it changes, widgets get moved as well.
/// </summary>
protected override void OnStart ()
{
mLayer = mGo.layer;
UICamera uic = UICamera.FindCameraForLayer(mLayer);
mCam = (uic != null) ? uic.cachedCamera : NGUITools.FindCameraForLayer(mLayer);
}
/// <summary>
/// Mark all widgets as having been changed so the draw calls get re-created.
/// </summary>
protected override void OnInit ()
{
base.OnInit();
// Apparently having a rigidbody helps
if (rigidbody == null)
{
Rigidbody rb = gameObject.AddComponent<Rigidbody>();
rb.isKinematic = true;
rb.useGravity = false;
}
mRebuild = true;
mAlphaFrameID = -1;
mMatrixFrame = -1;
list.Add(this);
list.Sort(CompareFunc);
}
/// <summary>
/// Destroy all draw calls we've created when this script gets disabled.
/// </summary>
protected override void OnDisable ()
{
for (int i = 0; i < drawCalls.size; ++i)
{
UIDrawCall dc = drawCalls.buffer[i];
if (dc != null) UIDrawCall.Destroy(dc);
}
drawCalls.Clear();
list.Remove(this);
mAlphaFrameID = -1;
mMatrixFrame = -1;
if (list.size == 0)
{
UIDrawCall.ReleaseAll();
mUpdateFrame = -1;
}
base.OnDisable();
}
/// <summary>
/// Update the world-to-local transform matrix as well as clipping bounds.
/// </summary>
void UpdateTransformMatrix ()
{
int fc = Time.frameCount;
if (mMatrixFrame != fc)
{
mMatrixFrame = fc;
worldToLocal = cachedTransform.worldToLocalMatrix;
Vector2 size = GetViewSize() * 0.5f;
float x = mClipOffset.x + mClipRange.x;
float y = mClipOffset.y + mClipRange.y;
mMin.x = x - size.x;
mMin.y = y - size.y;
mMax.x = x + size.x;
mMax.y = y + size.y;
}
}
/// <summary>
/// Update the edges after the anchors have been updated.
/// </summary>
protected override void OnAnchor ()
{
// No clipping = no edges to anchor
if (mClipping == UIDrawCall.Clipping.None) return;
Transform trans = cachedTransform;
Transform parent = trans.parent;
Vector2 size = GetViewSize();
Vector2 offset = trans.localPosition;
float lt, bt, rt, tt;
// Attempt to fast-path if all anchors match
if (leftAnchor.target == bottomAnchor.target &&
leftAnchor.target == rightAnchor.target &&
leftAnchor.target == topAnchor.target)
{
Vector3[] sides = leftAnchor.GetSides(parent);
if (sides != null)
{
lt = NGUIMath.Lerp(sides[0].x, sides[2].x, leftAnchor.relative) + leftAnchor.absolute;
rt = NGUIMath.Lerp(sides[0].x, sides[2].x, rightAnchor.relative) + rightAnchor.absolute;
bt = NGUIMath.Lerp(sides[3].y, sides[1].y, bottomAnchor.relative) + bottomAnchor.absolute;
tt = NGUIMath.Lerp(sides[3].y, sides[1].y, topAnchor.relative) + topAnchor.absolute;
}
else
{
// Anchored to a single transform
Vector2 lp = GetLocalPos(leftAnchor, parent);
lt = lp.x + leftAnchor.absolute;
bt = lp.y + bottomAnchor.absolute;
rt = lp.x + rightAnchor.absolute;
tt = lp.y + topAnchor.absolute;
}
}
else
{
// Left anchor point
if (leftAnchor.target)
{
Vector3[] sides = leftAnchor.GetSides(parent);
if (sides != null)
{
lt = NGUIMath.Lerp(sides[0].x, sides[2].x, leftAnchor.relative) + leftAnchor.absolute;
}
else
{
lt = GetLocalPos(leftAnchor, parent).x + leftAnchor.absolute;
}
}
else lt = mClipRange.x - 0.5f * size.x;
// Right anchor point
if (rightAnchor.target)
{
Vector3[] sides = rightAnchor.GetSides(parent);
if (sides != null)
{
rt = NGUIMath.Lerp(sides[0].x, sides[2].x, rightAnchor.relative) + rightAnchor.absolute;
}
else
{
rt = GetLocalPos(rightAnchor, parent).x + rightAnchor.absolute;
}
}
else rt = mClipRange.x + 0.5f * size.x;
// Bottom anchor point
if (bottomAnchor.target)
{
Vector3[] sides = bottomAnchor.GetSides(parent);
if (sides != null)
{
bt = NGUIMath.Lerp(sides[3].y, sides[1].y, bottomAnchor.relative) + bottomAnchor.absolute;
}
else
{
bt = GetLocalPos(bottomAnchor, parent).y + bottomAnchor.absolute;
}
}
else bt = mClipRange.y - 0.5f * size.y;
// Top anchor point
if (topAnchor.target)
{
Vector3[] sides = topAnchor.GetSides(parent);
if (sides != null)
{
tt = NGUIMath.Lerp(sides[3].y, sides[1].y, topAnchor.relative) + topAnchor.absolute;
}
else
{
tt = GetLocalPos(topAnchor, parent).y + topAnchor.absolute;
}
}
else tt = mClipRange.y + 0.5f * size.y;
}
// Take the offset into consideration
lt -= offset.x + mClipOffset.x;
rt -= offset.x + mClipOffset.x;
bt -= offset.y + mClipOffset.y;
tt -= offset.y + mClipOffset.y;
// Calculate the new position, width and height
float newX = Mathf.Lerp(lt, rt, 0.5f);
float newY = Mathf.Lerp(bt, tt, 0.5f);
float w = rt - lt;
float h = tt - bt;
float minx = Mathf.Max(20f, mClipSoftness.x);
float miny = Mathf.Max(20f, mClipSoftness.y);
if (w < minx) w = minx;
if (h < miny) h = miny;
// Update the clipping range
baseClipRegion = new Vector4(newX, newY, w, h);
}
static int mUpdateFrame = -1;
/// <summary>
/// Update all panels and draw calls.
/// </summary>
void LateUpdate ()
{
if (mUpdateFrame != Time.frameCount)
{
mUpdateFrame = Time.frameCount;
// Update each panel in order
for (int i = 0; i < list.size; ++i)
list[i].UpdateSelf();
int rq = 3000;
// Update all draw calls, making them draw in the right order
for (int i = 0; i < list.size; ++i)
{
UIPanel p = list.buffer[i];
if (p.renderQueue == RenderQueue.Automatic)
{
p.startingRenderQueue = rq;
p.UpdateDrawCalls();
rq += p.drawCalls.size;
}
else if (p.renderQueue == RenderQueue.StartAt)
{
p.UpdateDrawCalls();
if (p.drawCalls.size != 0)
rq = Mathf.Max(rq, p.startingRenderQueue + p.drawCalls.size);
}
else // Explicit
{
p.UpdateDrawCalls();
if (p.drawCalls.size != 0)
rq = Mathf.Max(rq, p.startingRenderQueue + 1);
}
}
}
}
/// <summary>
/// Update the panel, all of its widgets and draw calls.
/// </summary>
void UpdateSelf ()
{
mUpdateTime = RealTime.time;
UpdateTransformMatrix();
UpdateLayers();
UpdateWidgets();
if (mRebuild)
{
mRebuild = false;
FillAllDrawCalls();
}
else
{
for (int i = 0; i < drawCalls.size; )
{
UIDrawCall dc = drawCalls.buffer[i];
if (dc.isDirty && !FillDrawCall(dc))
{
UIDrawCall.Destroy(dc);
drawCalls.RemoveAt(i);
continue;
}
++i;
}
}
}
/// <summary>
/// Immediately sort all child widgets.
/// </summary>
public void SortWidgets ()
{
mSortWidgets = false;
widgets.Sort(UIWidget.PanelCompareFunc);
}
/// <summary>
/// Fill the geometry fully, processing all widgets and re-creating all draw calls.
/// </summary>
void FillAllDrawCalls ()
{
for (int i = 0; i < drawCalls.size; ++i)
UIDrawCall.Destroy(drawCalls.buffer[i]);
drawCalls.Clear();
Material mat = null;
Texture tex = null;
Shader sdr = null;
UIDrawCall dc = null;
if (mSortWidgets) SortWidgets();
for (int i = 0; i < widgets.size; ++i)
{
UIWidget w = widgets.buffer[i];
if (w.isVisible && w.hasVertices)
{
Material mt = w.material;
Texture tx = w.mainTexture;
Shader sd = w.shader;
if (mat != mt || tex != tx || sdr != sd)
{
if (dc != null && dc.verts.size != 0)
{
drawCalls.Add(dc);
dc.UpdateGeometry();
dc = null;
}
mat = mt;
tex = tx;
sdr = sd;
}
if (mat != null || sdr != null || tex != null)
{
if (dc == null)
{
dc = UIDrawCall.Create(this, mat, tex, sdr);
dc.depthStart = w.depth;
dc.depthEnd = dc.depthStart;
dc.panel = this;
}
else
{
int rd = w.depth;
if (rd < dc.depthStart) dc.depthStart = rd;
if (rd > dc.depthEnd) dc.depthEnd = rd;
}
w.drawCall = dc;
if (generateNormals) w.WriteToBuffers(dc.verts, dc.uvs, dc.cols, dc.norms, dc.tans);
else w.WriteToBuffers(dc.verts, dc.uvs, dc.cols, null, null);
}
}
else w.drawCall = null;
}
if (dc != null && dc.verts.size != 0)
{
drawCalls.Add(dc);
dc.UpdateGeometry();
}
}
/// <summary>
/// Fill the geometry for the specified draw call.
/// </summary>
bool FillDrawCall (UIDrawCall dc)
{
if (dc != null)
{
dc.isDirty = false;
for (int i = 0; i < widgets.size; )
{
UIWidget w = widgets[i];
if (w == null)
{
#if UNITY_EDITOR
Debug.LogError("This should never happen");
#endif
widgets.RemoveAt(i);
continue;
}
if (w.drawCall == dc)
{
if (w.isVisible && w.hasVertices)
{
if (generateNormals) w.WriteToBuffers(dc.verts, dc.uvs, dc.cols, dc.norms, dc.tans);
else w.WriteToBuffers(dc.verts, dc.uvs, dc.cols, null, null);
}
else w.drawCall = null;
}
++i;
}
if (dc.verts.size != 0)
{
dc.UpdateGeometry();
return true;
}
}
return false;
}
/// <summary>
/// Update all draw calls associated with the panel.
/// </summary>
void UpdateDrawCalls ()
{
Transform trans = cachedTransform;
bool isUI = usedForUI;
if (clipping != UIDrawCall.Clipping.None)
{
drawCallClipRange = finalClipRegion;
drawCallClipRange.z *= 0.5f;
drawCallClipRange.w *= 0.5f;
}
else drawCallClipRange = Vector4.zero;
// Legacy functionality
if (drawCallClipRange.z == 0f) drawCallClipRange.z = Screen.width * 0.5f;
if (drawCallClipRange.w == 0f) drawCallClipRange.w = Screen.height * 0.5f;
// DirectX 9 half-pixel offset
if (halfPixelOffset)
{
drawCallClipRange.x -= 0.5f;
drawCallClipRange.y += 0.5f;
}
Vector3 pos;
// We want the position to always be on even pixels so that the
// panel's contents always appear pixel-perfect.
if (isUI)
{
Transform parent = cachedTransform.parent;
pos = cachedTransform.localPosition;
if (parent != null)
{
float x = Mathf.Round(pos.x);
float y = Mathf.Round(pos.y);
drawCallClipRange.x += pos.x - x;
drawCallClipRange.y += pos.y - y;
pos.x = x;
pos.y = y;
pos = parent.TransformPoint(pos);
}
pos += drawCallOffset;
}
else pos = trans.position;
Quaternion rot = trans.rotation;
Vector3 scale = trans.lossyScale;
for (int i = 0; i < drawCalls.size; ++i)
{
UIDrawCall dc = drawCalls.buffer[i];
Transform t = dc.cachedTransform;
t.position = pos;
t.rotation = rot;
t.localScale = scale;
dc.renderQueue = (renderQueue == RenderQueue.Explicit) ? startingRenderQueue : startingRenderQueue + i;
dc.alwaysOnScreen = alwaysOnScreen &&
(mClipping == UIDrawCall.Clipping.None || mClipping == UIDrawCall.Clipping.ConstrainButDontClip);
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
dc.sortingOrder = mSortingOrder;
#endif
}
}
/// <summary>
/// Update the widget layers if the panel's layer has changed.
/// </summary>
void UpdateLayers ()
{
// Always move widgets to the panel's layer
if (mLayer != cachedGameObject.layer)
{
mLayer = mGo.layer;
UICamera uic = UICamera.FindCameraForLayer(mLayer);
mCam = (uic != null) ? uic.cachedCamera : NGUITools.FindCameraForLayer(mLayer);
NGUITools.SetChildLayer(cachedTransform, mLayer);
for (int i = 0; i < drawCalls.size; ++i)
drawCalls.buffer[i].gameObject.layer = mLayer;
}
}
bool mForced = false;
/// <summary>
/// Update all of the widgets belonging to this panel.
/// </summary>
void UpdateWidgets()
{
#if UNITY_EDITOR
bool forceVisible = cullWhileDragging ? false : (Application.isPlaying && mCullTime > mUpdateTime);
#else
bool forceVisible = cullWhileDragging ? false : (mCullTime > mUpdateTime);
#endif
bool changed = false;
if (mForced != forceVisible)
{
mForced = forceVisible;
mResized = true;
}
bool clipped = hasCumulativeClipping;
// Update all widgets
for (int i = 0, imax = widgets.size; i < imax; ++i)
{
UIWidget w = widgets.buffer[i];
// If the widget is visible, update it
if (w.panel == this && w.enabled)
{
#if UNITY_EDITOR
// When an object is dragged from Project view to Scene view, its Z is...
// odd, to say the least. Force it if possible.
if (!Application.isPlaying)
{
Transform t = w.cachedTransform;
if (t.hideFlags != HideFlags.HideInHierarchy)
{
t = (t.parent != null && t.parent.hideFlags == HideFlags.HideInHierarchy) ?
t.parent : null;
}
if (t != null)
{
for (; ; )
{
if (t.parent == null) break;
if (t.parent.hideFlags == HideFlags.HideInHierarchy) t = t.parent;
else break;
}
if (t != null)
{
Vector3 pos = t.localPosition;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
pos.z = 0f;
if (Vector3.SqrMagnitude(t.localPosition - pos) > 0.0001f)
t.localPosition = pos;
}
}
}
#endif
int frame = Time.frameCount;
// First update the widget's transform
if (w.UpdateTransform(frame) || mResized)
{
// Only proceed to checking the widget's visibility if it actually moved
bool vis = forceVisible || (w.CalculateCumulativeAlpha(frame) > 0.001f);
w.UpdateVisibility(vis, forceVisible || ((clipped || w.hideIfOffScreen) ? IsVisible(w) : true));
}
// Update the widget's geometry if necessary
if (w.UpdateGeometry(frame))
{
changed = true;
if (!mRebuild)
{
if (w.drawCall != null)
{
w.drawCall.isDirty = true;
}
else
{
// Find an existing draw call, if possible
FindDrawCall(w);
}
}
}
}
}
// Inform the changed event listeners
if (changed && onGeometryUpdated != null) onGeometryUpdated();
mResized = false;
}
/// <summary>
/// Insert the specified widget into one of the existing draw calls if possible.
/// If it's not possible, and a new draw call is required, 'null' is returned
/// because draw call creation is a delayed operation.
/// </summary>
public UIDrawCall FindDrawCall (UIWidget w)
{
Material mat = w.material;
Texture tex = w.mainTexture;
int depth = w.depth;
for (int i = 0; i < drawCalls.size; ++i)
{
UIDrawCall dc = drawCalls.buffer[i];
int dcStart = (i == 0) ? int.MinValue : drawCalls.buffer[i - 1].depthEnd + 1;
int dcEnd = (i + 1 == drawCalls.size) ? int.MaxValue : drawCalls.buffer[i + 1].depthStart - 1;
if (dcStart <= depth && dcEnd >= depth)
{
if (dc.baseMaterial == mat && dc.mainTexture == tex)
{
if (w.isVisible)
{
w.drawCall = dc;
if (w.hasVertices) dc.isDirty = true;
return dc;
}
}
else mRebuild = true;
return null;
}
}
mRebuild = true;
return null;
}
/// <summary>
/// Make the following widget be managed by the panel.
/// </summary>
public void AddWidget (UIWidget w)
{
if (widgets.size == 0)
{
widgets.Add(w);
}
else if (mSortWidgets)
{
widgets.Add(w);
SortWidgets();
}
else if (UIWidget.PanelCompareFunc(w, widgets[0]) == -1)
{
widgets.Insert(0, w);
}
else
{
for (int i = widgets.size; i > 0; )
{
if (UIWidget.PanelCompareFunc(w, widgets[--i]) == -1) continue;
widgets.Insert(i+1, w);
break;
}
}
FindDrawCall(w);
}
/// <summary>
/// Remove the widget from its current draw call, invalidating everything as needed.
/// </summary>
public void RemoveWidget (UIWidget w)
{
if (widgets.Remove(w) && w.drawCall != null)
{
int depth = w.depth;
if (depth == w.drawCall.depthStart || depth == w.drawCall.depthEnd)
mRebuild = true;
w.drawCall.isDirty = true;
w.drawCall = null;
}
}
/// <summary>
/// Immediately refresh the panel.
/// </summary>
public void Refresh ()
{
mRebuild = true;
if (list.size > 0) list[0].LateUpdate();
}
/// <summary>
/// Calculate the offset needed to be constrained within the panel's bounds.
/// </summary>
public virtual Vector3 CalculateConstrainOffset (Vector2 min, Vector2 max)
{
Vector4 cr = finalClipRegion;
float offsetX = cr.z * 0.5f;
float offsetY = cr.w * 0.5f;
Vector2 minRect = new Vector2(min.x, min.y);
Vector2 maxRect = new Vector2(max.x, max.y);
Vector2 minArea = new Vector2(cr.x - offsetX, cr.y - offsetY);
Vector2 maxArea = new Vector2(cr.x + offsetX, cr.y + offsetY);
if (clipping == UIDrawCall.Clipping.SoftClip)
{
minArea.x += clipSoftness.x;
minArea.y += clipSoftness.y;
maxArea.x -= clipSoftness.x;
maxArea.y -= clipSoftness.y;
}
return NGUIMath.ConstrainRect(minRect, maxRect, minArea, maxArea);
}
/// <summary>
/// Constrain the current target position to be within panel bounds.
/// </summary>
public bool ConstrainTargetToBounds (Transform target, ref Bounds targetBounds, bool immediate)
{
Vector3 offset = CalculateConstrainOffset(targetBounds.min, targetBounds.max);
if (offset.sqrMagnitude > 0f)
{
if (immediate)
{
target.localPosition += offset;
targetBounds.center += offset;
SpringPosition sp = target.GetComponent<SpringPosition>();
if (sp != null) sp.enabled = false;
}
else
{
SpringPosition sp = SpringPosition.Begin(target.gameObject, target.localPosition + offset, 13f);
sp.ignoreTimeScale = true;
sp.worldSpace = false;
}
return true;
}
return false;
}
/// <summary>
/// Constrain the specified target to be within the panel's bounds.
/// </summary>
public bool ConstrainTargetToBounds (Transform target, bool immediate)
{
Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(cachedTransform, target);
return ConstrainTargetToBounds(target, ref bounds, immediate);
}
/// <summary>
/// Find the UIPanel responsible for handling the specified transform.
/// </summary>
static public UIPanel Find (Transform trans) { return Find(trans, false, -1); }
/// <summary>
/// Find the UIPanel responsible for handling the specified transform.
/// </summary>
static public UIPanel Find (Transform trans, bool createIfMissing) { return Find(trans, createIfMissing, -1); }
/// <summary>
/// Find the UIPanel responsible for handling the specified transform.
/// </summary>
static public UIPanel Find (Transform trans, bool createIfMissing, int layer)
{
UIPanel panel = null;
while (panel == null && trans != null)
{
panel = trans.GetComponent<UIPanel>();
if (panel != null) return panel;
if (trans.parent == null) break;
trans = trans.parent;
}
return createIfMissing ? NGUITools.CreateUI(trans, false, layer) : null;
}
/// <summary>
/// Get the size of the game window in pixels.
/// </summary>
Vector2 GetWindowSize ()
{
UIRoot rt = root;
#if UNITY_EDITOR
Vector2 size = GetMainGameViewSize();
if (rt != null) size *= rt.GetPixelSizeAdjustment(Mathf.RoundToInt(size.y));
#else
Vector2 size = new Vector2(Screen.width, Screen.height);
if (rt != null) size *= rt.GetPixelSizeAdjustment(Screen.height);
#endif
return size;
}
/// <summary>
/// Panel's size -- which is either the clipping rect, or the screen dimensions.
/// </summary>
public Vector2 GetViewSize ()
{
bool clip = (mClipping != UIDrawCall.Clipping.None);
#if UNITY_EDITOR
Vector2 size = clip ? new Vector2(mClipRange.z, mClipRange.w) : GetMainGameViewSize();
#else
Vector2 size = clip ? new Vector2(mClipRange.z, mClipRange.w) : new Vector2(Screen.width, Screen.height);
#endif
if (!clip)
{
UIRoot rt = root;
#if UNITY_EDITOR
if (rt != null) size *= rt.GetPixelSizeAdjustment(Mathf.RoundToInt(size.y));
#else
if (rt != null) size *= rt.GetPixelSizeAdjustment(Screen.height);
#endif
}
return size;
}
#if UNITY_EDITOR
static int mSizeFrame = -1;
static System.Reflection.MethodInfo s_GetSizeOfMainGameView;
static Vector2 mGameSize = Vector2.one;
/// <summary>
/// Major hax to get the size of the game view window.
/// </summary>
static public Vector2 GetMainGameViewSize ()
{
int frame = Time.frameCount;
if (mSizeFrame != frame)
{
mSizeFrame = frame;
if (s_GetSizeOfMainGameView == null)
{
System.Type type = System.Type.GetType("UnityEditor.GameView,UnityEditor");
s_GetSizeOfMainGameView = type.GetMethod("GetSizeOfMainGameView",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
}
mGameSize = (Vector2)s_GetSizeOfMainGameView.Invoke(null, null);
}
return mGameSize;
}
/// <summary>
/// Draw a visible pink outline for the clipped area.
/// </summary>
void OnDrawGizmos ()
{
if (mCam == null) return;
Vector2 size = GetViewSize();
GameObject go = UnityEditor.Selection.activeGameObject;
bool selected = (go != null) && (NGUITools.FindInParents<UIPanel>(go) == this);
bool clip = (mClipping != UIDrawCall.Clipping.None);
Transform t = clip ? transform : (mCam != null ? mCam.transform : null);
if (t != null)
{
Vector3 pos = clip ? new Vector3(mClipOffset.x + mClipRange.x, mClipOffset.y + mClipRange.y) : Vector3.zero;
Gizmos.matrix = t.localToWorldMatrix;
if (selected)
{
if (mClipping == UIDrawCall.Clipping.SoftClip)
{
if (UnityEditor.Selection.activeGameObject == gameObject)
{
Gizmos.color = new Color(1f, 0f, 0.5f);
size.x -= mClipSoftness.x * 2f;
size.y -= mClipSoftness.y * 2f;
Gizmos.DrawWireCube(pos, size);
}
else
{
Gizmos.color = new Color(0.5f, 0f, 0.5f);
Gizmos.DrawWireCube(pos, size);
Gizmos.color = new Color(1f, 0f, 0.5f);
size.x -= mClipSoftness.x * 2f;
size.y -= mClipSoftness.y * 2f;
Gizmos.DrawWireCube(pos, size);
}
}
else
{
Gizmos.color = new Color(1f, 0f, 0.5f);
Gizmos.DrawWireCube(pos, size);
}
}
else
{
Gizmos.color = new Color(0.5f, 0f, 0.5f);
Gizmos.DrawWireCube(pos, size);
}
}
}
#endif
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIPanel.cs
|
C#
|
asf20
| 43,207
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
using System;
/// <summary>
/// UI Atlas contains a collection of sprites inside one large texture atlas.
/// </summary>
[AddComponentMenu("NGUI/UI/Atlas")]
public class UIAtlas : MonoBehaviour
{
// Legacy functionality, removed in 3.0. Do not use.
[System.Serializable]
class Sprite
{
public string name = "Unity Bug";
public Rect outer = new Rect(0f, 0f, 1f, 1f);
public Rect inner = new Rect(0f, 0f, 1f, 1f);
public bool rotated = false;
// Padding is needed for trimmed sprites and is relative to sprite width and height
public float paddingLeft = 0f;
public float paddingRight = 0f;
public float paddingTop = 0f;
public float paddingBottom = 0f;
public bool hasPadding { get { return paddingLeft != 0f || paddingRight != 0f || paddingTop != 0f || paddingBottom != 0f; } }
}
/// <summary>
/// Legacy functionality, removed in 3.0. Do not use.
/// </summary>
enum Coordinates
{
Pixels,
TexCoords,
}
// Material used by this atlas. Name is kept only for backwards compatibility, it used to be public.
[HideInInspector][SerializeField] Material material;
// List of all sprites inside the atlas. Name is kept only for backwards compatibility, it used to be public.
[HideInInspector][SerializeField] List<UISpriteData> mSprites = new List<UISpriteData>();
// Size in pixels for the sake of MakePixelPerfect functions.
[HideInInspector][SerializeField] float mPixelSize = 1f;
// Replacement atlas can be used to completely bypass this atlas, pulling the data from another one instead.
[HideInInspector][SerializeField] UIAtlas mReplacement;
// Legacy functionality -- do not use
[HideInInspector][SerializeField] Coordinates mCoordinates = Coordinates.Pixels;
[HideInInspector][SerializeField] List<Sprite> sprites = new List<Sprite>();
// Whether the atlas is using a pre-multiplied alpha material. -1 = not checked. 0 = no. 1 = yes.
int mPMA = -1;
/// <summary>
/// Material used by the atlas.
/// </summary>
public Material spriteMaterial
{
get
{
return (mReplacement != null) ? mReplacement.spriteMaterial : material;
}
set
{
if (mReplacement != null)
{
mReplacement.spriteMaterial = value;
}
else
{
if (material == null)
{
mPMA = 0;
material = value;
}
else
{
MarkAsChanged();
mPMA = -1;
material = value;
MarkAsChanged();
}
}
}
}
/// <summary>
/// Whether the atlas is using a premultiplied alpha material.
/// </summary>
public bool premultipliedAlpha
{
get
{
if (mReplacement != null) return mReplacement.premultipliedAlpha;
if (mPMA == -1)
{
Material mat = spriteMaterial;
mPMA = (mat != null && mat.shader != null && mat.shader.name.Contains("Premultiplied")) ? 1 : 0;
}
return (mPMA == 1);
}
}
/// <summary>
/// List of sprites within the atlas.
/// </summary>
public List<UISpriteData> spriteList
{
get
{
if (mReplacement != null) return mReplacement.spriteList;
if (mSprites.Count == 0) Upgrade();
return mSprites;
}
set
{
if (mReplacement != null)
{
mReplacement.spriteList = value;
}
else
{
mSprites = value;
}
}
}
/// <summary>
/// Texture used by the atlas.
/// </summary>
public Texture texture { get { return (mReplacement != null) ? mReplacement.texture : (material != null ? material.mainTexture as Texture : null); } }
/// <summary>
/// Pixel size is a multiplier applied to widgets dimensions when performing MakePixelPerfect() pixel correction.
/// Most obvious use would be on retina screen displays. The resolution doubles, but with UIRoot staying the same
/// for layout purposes, you can still get extra sharpness by switching to an HD atlas that has pixel size set to 0.5.
/// </summary>
public float pixelSize
{
get
{
return (mReplacement != null) ? mReplacement.pixelSize : mPixelSize;
}
set
{
if (mReplacement != null)
{
mReplacement.pixelSize = value;
}
else
{
float val = Mathf.Clamp(value, 0.25f, 4f);
if (mPixelSize != val)
{
mPixelSize = val;
MarkAsChanged();
}
}
}
}
/// <summary>
/// Setting a replacement atlas value will cause everything using this atlas to use the replacement atlas instead.
/// Suggested use: set up all your widgets to use a dummy atlas that points to the real atlas. Switching that atlas
/// to another one (for example an HD atlas) is then a simple matter of setting this field on your dummy atlas.
/// </summary>
public UIAtlas replacement
{
get
{
return mReplacement;
}
set
{
UIAtlas rep = value;
if (rep == this) rep = null;
if (mReplacement != rep)
{
if (rep != null && rep.replacement == this) rep.replacement = null;
if (mReplacement != null) MarkAsChanged();
mReplacement = rep;
MarkAsChanged();
}
}
}
/// <summary>
/// Convenience function that retrieves a sprite by name.
/// </summary>
public UISpriteData GetSprite (string name)
{
if (mReplacement != null)
{
return mReplacement.GetSprite(name);
}
else if (!string.IsNullOrEmpty(name))
{
if (mSprites.Count == 0) Upgrade();
for (int i = 0, imax = mSprites.Count; i < imax; ++i)
{
UISpriteData s = mSprites[i];
// string.Equals doesn't seem to work with Flash export
if (!string.IsNullOrEmpty(s.name) && name == s.name)
return s;
}
}
return null;
}
/// <summary>
/// Sort the list of sprites within the atlas, making them alphabetical.
/// </summary>
public void SortAlphabetically ()
{
mSprites.Sort(delegate(UISpriteData s1, UISpriteData s2) { return s1.name.CompareTo(s2.name); });
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
/// <summary>
/// Convenience function that retrieves a list of all sprite names.
/// </summary>
public BetterList<string> GetListOfSprites ()
{
if (mReplacement != null) return mReplacement.GetListOfSprites();
if (mSprites.Count == 0) Upgrade();
BetterList<string> list = new BetterList<string>();
for (int i = 0, imax = mSprites.Count; i < imax; ++i)
{
UISpriteData s = mSprites[i];
if (s != null && !string.IsNullOrEmpty(s.name)) list.Add(s.name);
}
return list;
}
/// <summary>
/// Convenience function that retrieves a list of all sprite names that contain the specified phrase
/// </summary>
public BetterList<string> GetListOfSprites (string match)
{
if (mReplacement) return mReplacement.GetListOfSprites(match);
if (string.IsNullOrEmpty(match)) return GetListOfSprites();
if (mSprites.Count == 0) Upgrade();
BetterList<string> list = new BetterList<string>();
// First try to find an exact match
for (int i = 0, imax = mSprites.Count; i < imax; ++i)
{
UISpriteData s = mSprites[i];
if (s != null && !string.IsNullOrEmpty(s.name) && string.Equals(match, s.name, StringComparison.OrdinalIgnoreCase))
{
list.Add(s.name);
return list;
}
}
// No exact match found? Split up the search into space-separated components.
string[] keywords = match.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < keywords.Length; ++i) keywords[i] = keywords[i].ToLower();
// Try to find all sprites where all keywords are present
for (int i = 0, imax = mSprites.Count; i < imax; ++i)
{
UISpriteData s = mSprites[i];
if (s != null && !string.IsNullOrEmpty(s.name))
{
string tl = s.name.ToLower();
int matches = 0;
for (int b = 0; b < keywords.Length; ++b)
{
if (tl.Contains(keywords[b])) ++matches;
}
if (matches == keywords.Length) list.Add(s.name);
}
}
return list;
}
/// <summary>
/// Helper function that determines whether the atlas uses the specified one, taking replacements into account.
/// </summary>
bool References (UIAtlas atlas)
{
if (atlas == null) return false;
if (atlas == this) return true;
return (mReplacement != null) ? mReplacement.References(atlas) : false;
}
/// <summary>
/// Helper function that determines whether the two atlases are related.
/// </summary>
static public bool CheckIfRelated (UIAtlas a, UIAtlas b)
{
if (a == null || b == null) return false;
return a == b || a.References(b) || b.References(a);
}
/// <summary>
/// Mark all widgets associated with this atlas as having changed.
/// </summary>
public void MarkAsChanged ()
{
#if UNITY_EDITOR
NGUITools.SetDirty(gameObject);
#endif
if (mReplacement != null) mReplacement.MarkAsChanged();
UISprite[] list = NGUITools.FindActive<UISprite>();
for (int i = 0, imax = list.Length; i < imax; ++i)
{
UISprite sp = list[i];
if (CheckIfRelated(this, sp.atlas))
{
UIAtlas atl = sp.atlas;
sp.atlas = null;
sp.atlas = atl;
#if UNITY_EDITOR
NGUITools.SetDirty(sp);
#endif
}
}
UIFont[] fonts = Resources.FindObjectsOfTypeAll(typeof(UIFont)) as UIFont[];
for (int i = 0, imax = fonts.Length; i < imax; ++i)
{
UIFont font = fonts[i];
if (CheckIfRelated(this, font.atlas))
{
UIAtlas atl = font.atlas;
font.atlas = null;
font.atlas = atl;
#if UNITY_EDITOR
NGUITools.SetDirty(font);
#endif
}
}
UILabel[] labels = NGUITools.FindActive<UILabel>();
for (int i = 0, imax = labels.Length; i < imax; ++i)
{
UILabel lbl = labels[i];
if (lbl.bitmapFont != null && CheckIfRelated(this, lbl.bitmapFont.atlas))
{
UIFont font = lbl.bitmapFont;
lbl.bitmapFont = null;
lbl.bitmapFont = font;
#if UNITY_EDITOR
NGUITools.SetDirty(lbl);
#endif
}
}
}
/// <summary>
/// Performs an upgrade from the legacy way of specifying data to the new one.
/// </summary>
bool Upgrade ()
{
if (mReplacement) return mReplacement.Upgrade();
if (mSprites.Count == 0 && sprites.Count > 0 && material)
{
Texture tex = material.mainTexture;
int width = (tex != null) ? tex.width : 512;
int height = (tex != null) ? tex.height : 512;
for (int i = 0; i < sprites.Count; ++i)
{
Sprite old = sprites[i];
Rect outer = old.outer;
Rect inner = old.inner;
if (mCoordinates == Coordinates.TexCoords)
{
NGUIMath.ConvertToPixels(outer, width, height, true);
NGUIMath.ConvertToPixels(inner, width, height, true);
}
UISpriteData sd = new UISpriteData();
sd.name = old.name;
sd.x = Mathf.RoundToInt(outer.xMin);
sd.y = Mathf.RoundToInt(outer.yMin);
sd.width = Mathf.RoundToInt(outer.width);
sd.height = Mathf.RoundToInt(outer.height);
sd.paddingLeft = Mathf.RoundToInt(old.paddingLeft * outer.width);
sd.paddingRight = Mathf.RoundToInt(old.paddingRight * outer.width);
sd.paddingBottom = Mathf.RoundToInt(old.paddingBottom * outer.height);
sd.paddingTop = Mathf.RoundToInt(old.paddingTop * outer.height);
sd.borderLeft = Mathf.RoundToInt(inner.xMin - outer.xMin);
sd.borderRight = Mathf.RoundToInt(outer.xMax - inner.xMax);
sd.borderBottom = Mathf.RoundToInt(outer.yMax - inner.yMax);
sd.borderTop = Mathf.RoundToInt(inner.yMin - outer.yMin);
mSprites.Add(sd);
}
sprites.Clear();
#if UNITY_EDITOR
NGUITools.SetDirty(this);
UnityEditor.AssetDatabase.SaveAssets();
#endif
return true;
}
return false;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIAtlas.cs
|
C#
|
asf20
| 11,467
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Sprite is a textured element in the UI hierarchy.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/NGUI Sprite")]
public class UISprite : UIWidget
{
public enum Type
{
Simple,
Sliced,
Tiled,
Filled,
Advanced,
}
public enum FillDirection
{
Horizontal,
Vertical,
Radial90,
Radial180,
Radial360,
}
public enum AdvancedType
{
Invisible,
Sliced,
Tiled,
}
public enum Flip
{
Nothing,
Horizontally,
Vertically,
Both,
}
// Cached and saved values
[HideInInspector][SerializeField] UIAtlas mAtlas;
[HideInInspector][SerializeField] string mSpriteName;
[HideInInspector][SerializeField] Type mType = Type.Simple;
[HideInInspector][SerializeField] FillDirection mFillDirection = FillDirection.Radial360;
#if !UNITY_3_5
[Range(0f, 1f)]
#endif
[HideInInspector][SerializeField] float mFillAmount = 1.0f;
[HideInInspector][SerializeField] bool mInvert = false;
[HideInInspector][SerializeField] Flip mFlip = Flip.Nothing;
// Deprecated, no longer used
[HideInInspector][SerializeField] bool mFillCenter = true;
[System.NonSerialized]
protected UISpriteData mSprite;
protected Rect mInnerUV = new Rect();
protected Rect mOuterUV = new Rect();
bool mSpriteSet = false;
/// <summary>
/// When the sprite type is advanced, this determines whether the center is tiled or sliced.
/// </summary>
public AdvancedType centerType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the left edge is tiled or sliced.
/// </summary>
public AdvancedType leftType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the right edge is tiled or sliced.
/// </summary>
public AdvancedType rightType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the bottom edge is tiled or sliced.
/// </summary>
public AdvancedType bottomType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the top edge is tiled or sliced.
/// </summary>
public AdvancedType topType = AdvancedType.Sliced;
/// <summary>
/// How the sprite is drawn.
/// </summary>
public virtual Type type
{
get
{
return mType;
}
set
{
if (mType != value)
{
mType = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite flip setting.
/// </summary>
public Flip flip
{
get
{
return mFlip;
}
set
{
if (mFlip != value)
{
mFlip = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Retrieve the material used by the font.
/// </summary>
public override Material material { get { return (mAtlas != null) ? mAtlas.spriteMaterial : null; } }
/// <summary>
/// Atlas used by this widget.
/// </summary>
public UIAtlas atlas
{
get
{
return mAtlas;
}
set
{
if (mAtlas != value)
{
RemoveFromPanel();
mAtlas = value;
mSpriteSet = false;
mSprite = null;
// Automatically choose the first sprite
if (string.IsNullOrEmpty(mSpriteName))
{
if (mAtlas != null && mAtlas.spriteList.Count > 0)
{
SetAtlasSprite(mAtlas.spriteList[0]);
mSpriteName = mSprite.name;
}
}
// Re-link the sprite
if (!string.IsNullOrEmpty(mSpriteName))
{
string sprite = mSpriteName;
mSpriteName = "";
spriteName = sprite;
MarkAsChanged();
}
}
}
}
/// <summary>
/// Sprite within the atlas used to draw this widget.
/// </summary>
public string spriteName
{
get
{
return mSpriteName;
}
set
{
if (string.IsNullOrEmpty(value))
{
// If the sprite name hasn't been set yet, no need to do anything
if (string.IsNullOrEmpty(mSpriteName)) return;
// Clear the sprite name and the sprite reference
mSpriteName = "";
mSprite = null;
mChanged = true;
mSpriteSet = false;
}
else if (mSpriteName != value)
{
// If the sprite name changes, the sprite reference should also be updated
mSpriteName = value;
mSprite = null;
mChanged = true;
mSpriteSet = false;
}
}
}
/// <summary>
/// Is there a valid sprite to work with?
/// </summary>
public bool isValid { get { return GetAtlasSprite() != null; } }
/// <summary>
/// Whether the center part of the sprite will be filled or not. Turn it off if you want only to borders to show up.
/// </summary>
[System.Obsolete("Use 'centerType' instead")]
public bool fillCenter
{
get
{
return centerType != AdvancedType.Invisible;
}
set
{
if (value != (centerType != AdvancedType.Invisible))
{
centerType = value ? AdvancedType.Sliced : AdvancedType.Invisible;
MarkAsChanged();
}
}
}
/// <summary>
/// Direction of the cut procedure.
/// </summary>
public FillDirection fillDirection
{
get
{
return mFillDirection;
}
set
{
if (mFillDirection != value)
{
mFillDirection = value;
mChanged = true;
}
}
}
/// <summary>
/// Amount of the sprite shown. 0-1 range with 0 being nothing shown, and 1 being the full sprite.
/// </summary>
public float fillAmount
{
get
{
return mFillAmount;
}
set
{
float val = Mathf.Clamp01(value);
if (mFillAmount != val)
{
mFillAmount = val;
mChanged = true;
}
}
}
/// <summary>
/// Whether the sprite should be filled in the opposite direction.
/// </summary>
public bool invert
{
get
{
return mInvert;
}
set
{
if (mInvert != value)
{
mInvert = value;
mChanged = true;
}
}
}
/// <summary>
/// Sliced sprites generally have a border. X = left, Y = bottom, Z = right, W = top.
/// </summary>
public override Vector4 border
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
UISpriteData sp = GetAtlasSprite();
if (sp == null) return Vector2.zero;
return new Vector4(sp.borderLeft, sp.borderBottom, sp.borderRight, sp.borderTop);
}
return base.border;
}
}
/// <summary>
/// Minimum allowed width for this widget.
/// </summary>
override public int minWidth
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border;
if (atlas != null) b *= atlas.pixelSize;
int min = Mathf.RoundToInt(b.x + b.z);
UISpriteData sp = GetAtlasSprite();
if (sp != null) min += sp.paddingLeft + sp.paddingRight;
return Mathf.Max(base.minWidth, ((min & 1) == 1) ? min + 1 : min);
}
return base.minWidth;
}
}
/// <summary>
/// Minimum allowed height for this widget.
/// </summary>
override public int minHeight
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border;
if (atlas != null) b *= atlas.pixelSize;
int min = Mathf.RoundToInt(b.y + b.w);
UISpriteData sp = GetAtlasSprite();
if (sp != null) min += sp.paddingTop + sp.paddingBottom;
return Mathf.Max(base.minHeight, ((min & 1) == 1) ? min + 1 : min);
}
return base.minHeight;
}
}
#if UNITY_EDITOR
/// <summary>
/// Keep sane values.
/// </summary>
protected override void OnValidate ()
{
base.OnValidate();
mFillAmount = Mathf.Clamp01(mFillAmount);
}
#endif
/// <summary>
/// Retrieve the atlas sprite referenced by the spriteName field.
/// </summary>
public UISpriteData GetAtlasSprite ()
{
if (!mSpriteSet) mSprite = null;
if (mSprite == null && mAtlas != null)
{
if (!string.IsNullOrEmpty(mSpriteName))
{
UISpriteData sp = mAtlas.GetSprite(mSpriteName);
if (sp == null) return null;
SetAtlasSprite(sp);
}
if (mSprite == null && mAtlas.spriteList.Count > 0)
{
UISpriteData sp = mAtlas.spriteList[0];
if (sp == null) return null;
SetAtlasSprite(sp);
if (mSprite == null)
{
Debug.LogError(mAtlas.name + " seems to have a null sprite!");
return null;
}
mSpriteName = mSprite.name;
}
}
return mSprite;
}
/// <summary>
/// Set the atlas sprite directly.
/// </summary>
protected void SetAtlasSprite (UISpriteData sp)
{
mChanged = true;
mSpriteSet = true;
if (sp != null)
{
mSprite = sp;
mSpriteName = mSprite.name;
}
else
{
mSpriteName = (mSprite != null) ? mSprite.name : "";
mSprite = sp;
}
}
/// <summary>
/// Adjust the scale of the widget to make it pixel-perfect.
/// </summary>
public override void MakePixelPerfect ()
{
if (!isValid) return;
base.MakePixelPerfect();
UISpriteData sp = GetAtlasSprite();
if (sp == null) return;
UISprite.Type t = type;
if (t == Type.Simple || t == Type.Filled || !sp.hasBorder)
{
Texture tex = mainTexture;
if (tex != null && sp != null)
{
int x = Mathf.RoundToInt(atlas.pixelSize * (sp.width + sp.paddingLeft + sp.paddingRight));
int y = Mathf.RoundToInt(atlas.pixelSize * (sp.height + sp.paddingTop + sp.paddingBottom));
if ((x & 1) == 1) ++x;
if ((y & 1) == 1) ++y;
width = x;
height = y;
}
}
}
/// <summary>
/// Auto-upgrade.
/// </summary>
protected override void OnInit ()
{
if (!mFillCenter)
{
mFillCenter = true;
centerType = AdvancedType.Invisible;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
base.OnInit();
}
/// <summary>
/// Update the UV coordinates.
/// </summary>
protected override void OnUpdate ()
{
base.OnUpdate();
if (mChanged || !mSpriteSet)
{
mSpriteSet = true;
mSprite = null;
mChanged = true;
}
}
/// <summary>
/// Virtual function called by the UIPanel that fills the buffers.
/// </summary>
public override void OnFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
if (mSprite == null) mSprite = atlas.GetSprite(spriteName);
if (mSprite == null) return;
mOuterUV.Set(mSprite.x, mSprite.y, mSprite.width, mSprite.height);
mInnerUV.Set(mSprite.x + mSprite.borderLeft, mSprite.y + mSprite.borderTop,
mSprite.width - mSprite.borderLeft - mSprite.borderRight,
mSprite.height - mSprite.borderBottom - mSprite.borderTop);
mOuterUV = NGUIMath.ConvertToTexCoords(mOuterUV, tex.width, tex.height);
mInnerUV = NGUIMath.ConvertToTexCoords(mInnerUV, tex.width, tex.height);
switch (type)
{
case Type.Simple:
SimpleFill(verts, uvs, cols);
break;
case Type.Sliced:
SlicedFill(verts, uvs, cols);
break;
case Type.Filled:
FilledFill(verts, uvs, cols);
break;
case Type.Tiled:
TiledFill(verts, uvs, cols);
break;
case Type.Advanced:
AdvancedFill(verts, uvs, cols);
break;
}
}
#region Various fill functions
// Static variables to reduce garbage collection
static Vector2[] mTempPos = new Vector2[4];
static Vector2[] mTempUVs = new Vector2[4];
/// <summary>
/// Sprite's dimensions used for drawing. X = left, Y = bottom, Z = right, W = top.
/// This function automatically adds 1 pixel on the edge if the sprite's dimensions are not even.
/// It's used to achieve pixel-perfect sprites even when an odd dimension sprite happens to be centered.
/// </summary>
public override Vector4 drawingDimensions
{
get
{
Vector2 offset = pivotOffset;
float x0 = -offset.x * mWidth;
float y0 = -offset.y * mHeight;
float x1 = x0 + mWidth;
float y1 = y0 + mHeight;
if (GetAtlasSprite() != null && mType != Type.Tiled)
{
int padLeft = mSprite.paddingLeft;
int padBottom = mSprite.paddingBottom;
int padRight = mSprite.paddingRight;
int padTop = mSprite.paddingTop;
int w = mSprite.width + padLeft + padRight;
int h = mSprite.height + padBottom + padTop;
float px = 1f;
float py = 1f;
if (w > 0 && h > 0 && (mType == Type.Simple || mType == Type.Filled))
{
if ((w & 1) != 0) ++padRight;
if ((h & 1) != 0) ++padTop;
px = (1f / w) * mWidth;
py = (1f / h) * mHeight;
}
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
x0 += padRight * px;
x1 -= padLeft * px;
}
else
{
x0 += padLeft * px;
x1 -= padRight * px;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
y0 += padTop * py;
y1 -= padBottom * py;
}
else
{
y0 += padBottom * py;
y1 -= padTop * py;
}
}
Vector4 br = (mAtlas != null) ? border * mAtlas.pixelSize : Vector4.zero;
float fw = br.x + br.z;
float fh = br.y + br.w;
float vx = Mathf.Lerp(x0, x1 - fw, mDrawRegion.x);
float vy = Mathf.Lerp(y0, y1 - fh, mDrawRegion.y);
float vz = Mathf.Lerp(x0 + fw, x1, mDrawRegion.z);
float vw = Mathf.Lerp(y0 + fh, y1, mDrawRegion.w);
return new Vector4(vx, vy, vz, vw);
}
}
/// <summary>
/// Convenience function that returns the drawn UVs after flipping gets considered.
/// X = left, Y = bottom, Z = right, W = top.
/// </summary>
protected virtual Vector4 drawingUVs
{
get
{
switch (mFlip)
{
case Flip.Horizontally: return new Vector4(mOuterUV.xMax, mOuterUV.yMin, mOuterUV.xMin, mOuterUV.yMax);
case Flip.Vertically: return new Vector4(mOuterUV.xMin, mOuterUV.yMax, mOuterUV.xMax, mOuterUV.yMin);
case Flip.Both: return new Vector4(mOuterUV.xMax, mOuterUV.yMax, mOuterUV.xMin, mOuterUV.yMin);
default: return new Vector4(mOuterUV.xMin, mOuterUV.yMin, mOuterUV.xMax, mOuterUV.yMax);
}
}
}
/// <summary>
/// Regular sprite fill function is quite simple.
/// </summary>
protected void SimpleFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
uvs.Add(new Vector2(u.x, u.y));
uvs.Add(new Vector2(u.x, u.w));
uvs.Add(new Vector2(u.z, u.w));
uvs.Add(new Vector2(u.z, u.y));
Color colF = color;
colF.a = finalAlpha;
Color32 col = atlas.premultipliedAlpha ? NGUITools.ApplyPMA(colF) : colF;
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
/// <summary>
/// Sliced sprite fill function is more complicated as it generates 9 quads instead of 1.
/// </summary>
protected void SlicedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (!mSprite.hasBorder)
{
SimpleFill(verts, uvs, cols);
return;
}
Vector4 dr = drawingDimensions;
Vector4 br = border * atlas.pixelSize;
mTempPos[0].x = dr.x;
mTempPos[0].y = dr.y;
mTempPos[3].x = dr.z;
mTempPos[3].y = dr.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
Color colF = color;
colF.a = finalAlpha;
Color32 col = atlas.premultipliedAlpha ? NGUITools.ApplyPMA(colF) : colF;
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y].y));
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y].y));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
}
}
/// <summary>
/// Tiled sprite fill function.
/// </summary>
protected void TiledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = material.mainTexture;
if (tex == null) return;
Vector4 v = drawingDimensions;
Vector4 u;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
u.x = mInnerUV.xMax;
u.z = mInnerUV.xMin;
}
else
{
u.x = mInnerUV.xMin;
u.z = mInnerUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
u.y = mInnerUV.yMax;
u.w = mInnerUV.yMin;
}
else
{
u.y = mInnerUV.yMin;
u.w = mInnerUV.yMax;
}
Vector2 size = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
size *= atlas.pixelSize;
// Don't tile really small sprites
if (size.x < 2f || size.y < 2f) return;
Color colF = color;
colF.a = finalAlpha;
Color32 col = atlas.premultipliedAlpha ? NGUITools.ApplyPMA(colF) : colF;
float x0 = v.x;
float y0 = v.y;
float u0 = u.x;
float v0 = u.y;
while (y0 < v.w)
{
x0 = v.x;
float y1 = y0 + size.y;
float v1 = u.w;
if (y1 > v.w)
{
v1 = Mathf.Lerp(u.y, u.w, (v.w - y0) / size.y);
y1 = v.w;
}
while (x0 < v.z)
{
float x1 = x0 + size.x;
float u1 = u.z;
if (x1 > v.z)
{
u1 = Mathf.Lerp(u.x, u.z, (v.z - x0) / size.x);
x1 = v.z;
}
verts.Add(new Vector3(x0, y0));
verts.Add(new Vector3(x0, y1));
verts.Add(new Vector3(x1, y1));
verts.Add(new Vector3(x1, y0));
uvs.Add(new Vector2(u0, v0));
uvs.Add(new Vector2(u0, v1));
uvs.Add(new Vector2(u1, v1));
uvs.Add(new Vector2(u1, v0));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
x0 += size.x;
}
y0 += size.y;
}
}
/// <summary>
/// Filled sprite fill function.
/// </summary>
protected void FilledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (mFillAmount < 0.001f) return;
Color colF = color;
colF.a = finalAlpha;
Color32 col = atlas.premultipliedAlpha ? NGUITools.ApplyPMA(colF) : colF;
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
// Horizontal and vertical filled sprites are simple -- just end the sprite prematurely
if (mFillDirection == FillDirection.Horizontal || mFillDirection == FillDirection.Vertical)
{
if (mFillDirection == FillDirection.Horizontal)
{
float fill = (u.z - u.x) * mFillAmount;
if (mInvert)
{
v.x = v.z - (v.z - v.x) * mFillAmount;
u.x = u.z - fill;
}
else
{
v.z = v.x + (v.z - v.x) * mFillAmount;
u.z = u.x + fill;
}
}
else if (mFillDirection == FillDirection.Vertical)
{
float fill = (u.w - u.y) * mFillAmount;
if (mInvert)
{
v.y = v.w - (v.w - v.y) * mFillAmount;
u.y = u.w - fill;
}
else
{
v.w = v.y + (v.w - v.y) * mFillAmount;
u.w = u.y + fill;
}
}
}
mTempPos[0] = new Vector2(v.x, v.y);
mTempPos[1] = new Vector2(v.x, v.w);
mTempPos[2] = new Vector2(v.z, v.w);
mTempPos[3] = new Vector2(v.z, v.y);
mTempUVs[0] = new Vector2(u.x, u.y);
mTempUVs[1] = new Vector2(u.x, u.w);
mTempUVs[2] = new Vector2(u.z, u.w);
mTempUVs[3] = new Vector2(u.z, u.y);
if (mFillAmount < 1f)
{
if (mFillDirection == FillDirection.Radial90)
{
if (RadialCut(mTempPos, mTempUVs, mFillAmount, mInvert, 0))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(col);
}
}
return;
}
if (mFillDirection == FillDirection.Radial180)
{
for (int side = 0; side < 2; ++side)
{
float fx0, fx1, fy0, fy1;
fy0 = 0f;
fy1 = 1f;
if (side == 0) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = !mInvert ? fillAmount * 2f - side : mFillAmount * 2f - (1 - side);
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), !mInvert, NGUIMath.RepeatIndex(side + 3, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(col);
}
}
}
return;
}
if (mFillDirection == FillDirection.Radial360)
{
for (int corner = 0; corner < 4; ++corner)
{
float fx0, fx1, fy0, fy1;
if (corner < 2) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; }
else { fy0 = 0.5f; fy1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = mInvert ?
mFillAmount * 4f - NGUIMath.RepeatIndex(corner + 2, 4) :
mFillAmount * 4f - (3 - NGUIMath.RepeatIndex(corner + 2, 4));
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), mInvert, NGUIMath.RepeatIndex(corner + 2, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(col);
}
}
}
return;
}
}
// Fill the buffer with the quad for the sprite
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(col);
}
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static bool RadialCut (Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner)
{
// Nothing to fill
if (fill < 0.001f) return false;
// Even corners invert the fill direction
if ((corner & 1) == 1) invert = !invert;
// Nothing to adjust
if (!invert && fill > 0.999f) return true;
// Convert 0-1 value into 0 to 90 degrees angle in radians
float angle = Mathf.Clamp01(fill);
if (invert) angle = 1f - angle;
angle *= 90f * Mathf.Deg2Rad;
// Calculate the effective X and Y factors
float cos = Mathf.Cos(angle);
float sin = Mathf.Sin(angle);
RadialCut(xy, cos, sin, invert, corner);
RadialCut(uv, cos, sin, invert, corner);
return true;
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static void RadialCut (Vector2[] xy, float cos, float sin, bool invert, int corner)
{
int i0 = corner;
int i1 = NGUIMath.RepeatIndex(corner + 1, 4);
int i2 = NGUIMath.RepeatIndex(corner + 2, 4);
int i3 = NGUIMath.RepeatIndex(corner + 3, 4);
if ((corner & 1) == 1)
{
if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i2].x = xy[i1].x;
}
}
else if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i3].y = xy[i2].y;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
}
else
{
if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i2].y = xy[i1].y;
}
}
else if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i3].x = xy[i2].x;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
}
}
/// <summary>
/// Advanced sprite fill function. Contributed by Nicki Hansen.
/// </summary>
protected void AdvancedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (!mSprite.hasBorder)
{
SimpleFill(verts, uvs, cols);
return;
}
Texture tex = material.mainTexture;
if (tex == null) return;
Vector4 dr = drawingDimensions;
Vector4 br = border * atlas.pixelSize;
Vector2 tileSize = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
tileSize *= atlas.pixelSize;
if (tileSize.x < 1f) tileSize.x = 1f;
if (tileSize.y < 1f) tileSize.y = 1f;
mTempPos[0].x = dr.x;
mTempPos[0].y = dr.y;
mTempPos[3].x = dr.z;
mTempPos[3].y = dr.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
Color colF = color;
colF.a = finalAlpha;
Color32 col = atlas.premultipliedAlpha ? NGUITools.ApplyPMA(colF) : colF;
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
if (x == 1 && y == 1) // Center
{
if (centerType == AdvancedType.Tiled)
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float tileStartX = startPositionX;
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
FillBuffers(tileStartX, tileEndX, tileStartY, tileEndY, textureStartX,
textureEndX, textureStartY, textureEndY, col, verts, uvs, cols);
tileStartX += tileSize.x;
}
tileStartY += tileSize.y;
}
}
else if (centerType == AdvancedType.Sliced)
{
FillBuffers(mTempPos[x].x, mTempPos[x2].x, mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x, mTempUVs[y].y, mTempUVs[y2].y, col, verts, uvs, cols);
}
}
else if (x == 1) // Top or bottom
{
if ((y == 0 && bottomType == AdvancedType.Tiled) || (y == 2 && topType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float textureEndY = mTempUVs[y2].y;
float tileStartX = startPositionX;
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
FillBuffers(tileStartX, tileEndX, startPositionY, endPositionY, textureStartX,
textureEndX, textureStartY, textureEndY, col, verts, uvs, cols);
tileStartX += tileSize.x;
}
}
else if ((y == 0 && bottomType == AdvancedType.Sliced) || (y == 2 && topType == AdvancedType.Sliced))
{
FillBuffers(mTempPos[x].x, mTempPos[x2].x, mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x, mTempUVs[y].y, mTempUVs[y2].y, col, verts, uvs, cols);
}
}
else if (y == 1) // Left or right
{
if ((x == 0 && leftType == AdvancedType.Tiled) || (x == 2 && rightType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureEndX = mTempUVs[x2].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
FillBuffers(startPositionX, endPositionX, tileStartY, tileEndY, textureStartX,
textureEndX, textureStartY, textureEndY, col, verts, uvs, cols);
tileStartY += tileSize.y;
}
}
else if ((x == 0 && leftType == AdvancedType.Sliced) || (x == 2 && rightType == AdvancedType.Sliced))
{
FillBuffers(mTempPos[x].x, mTempPos[x2].x, mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x, mTempUVs[y].y, mTempUVs[y2].y, col, verts, uvs, cols);
}
}
else // Corner
{
FillBuffers(mTempPos[x].x, mTempPos[x2].x, mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x, mTempUVs[y].y, mTempUVs[y2].y, col, verts, uvs, cols);
}
}
}
}
/// <summary>
/// Helper function used in AdvancedFill, above. Contributed by Nicki Hansen.
/// </summary>
void FillBuffers (float v0x, float v1x, float v0y, float v1y, float u0x, float u1x, float u0y, float u1y, Color col,
BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
uvs.Add(new Vector2(u0x, u0y));
uvs.Add(new Vector2(u0x, u1y));
uvs.Add(new Vector2(u1x, u1y));
uvs.Add(new Vector2(u1x, u0y));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
#endregion
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UISprite.cs
|
C#
|
asf20
| 32,631
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_FLASH
#define DYNAMIC_FONT
#endif
using UnityEngine;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Text list can be used with a UILabel to create a scrollable multi-line text field that's
/// easy to add new entries to. Optimal use: chat window.
/// </summary>
[AddComponentMenu("NGUI/UI/Text List")]
public class UITextList : MonoBehaviour
{
public enum Style
{
Text,
Chat,
}
/// <summary>
/// Label the contents of which will be modified with the chat entries.
/// </summary>
public UILabel textLabel;
/// <summary>
/// Vertical scroll bar associated with the text list.
/// </summary>
public UIProgressBar scrollBar;
/// <summary>
/// Text style. Text entries go top to bottom. Chat entries go bottom to top.
/// </summary>
public Style style = Style.Text;
/// <summary>
/// Maximum number of chat log entries to keep before discarding them.
/// </summary>
public int paragraphHistory = 50;
// Text list is made up of paragraphs
protected class Paragraph
{
public string text; // Original text
public string[] lines; // Split lines
}
protected char[] mSeparator = new char[] { '\n' };
protected BetterList<Paragraph> mParagraphs = new BetterList<Paragraph>();
protected float mScroll = 0f;
protected int mTotalLines = 0;
protected int mLastWidth = 0;
protected int mLastHeight = 0;
/// <summary>
/// Whether the text list is usable.
/// </summary>
#if DYNAMIC_FONT
public bool isValid { get { return textLabel != null && textLabel.ambigiousFont != null; } }
#else
public bool isValid { get { return textLabel != null && textLabel.bitmapFont != null; } }
#endif
/// <summary>
/// Relative (0-1 range) scroll value, with 0 being the oldest entry and 1 being the newest entry.
/// </summary>
public float scrollValue
{
get
{
return mScroll;
}
set
{
value = Mathf.Clamp01(value);
if (isValid && mScroll != value)
{
if (scrollBar != null)
{
scrollBar.value = value;
}
else
{
mScroll = value;
UpdateVisibleText();
}
}
}
}
/// <summary>
/// Height of each line.
/// </summary>
protected float lineHeight { get { return (textLabel != null) ? textLabel.fontSize + textLabel.spacingY : 20f; } }
/// <summary>
/// Height of the scrollable area (outside of the visible area's bounds).
/// </summary>
protected int scrollHeight
{
get
{
if (!isValid) return 0;
int maxLines = Mathf.FloorToInt((float)textLabel.height / lineHeight);
return Mathf.Max(0, mTotalLines - maxLines);
}
}
/// <summary>
/// Clear the text.
/// </summary>
public void Clear ()
{
mParagraphs.Clear();
UpdateVisibleText();
}
/// <summary>
/// Automatically find the values if none were specified.
/// </summary>
void Start ()
{
if (textLabel == null)
textLabel = GetComponentInChildren<UILabel>();
if (scrollBar != null)
EventDelegate.Add(scrollBar.onChange, OnScrollBar);
textLabel.overflowMethod = UILabel.Overflow.ClampContent;
if (style == Style.Chat)
{
textLabel.pivot = UIWidget.Pivot.BottomLeft;
scrollValue = 1f;
}
else
{
textLabel.pivot = UIWidget.Pivot.TopLeft;
scrollValue = 0f;
}
}
/// <summary>
/// Keep an eye on the size of the label, and if it changes -- rebuild everything.
/// </summary>
void Update ()
{
if (isValid)
{
if (textLabel.width != mLastWidth || textLabel.height != mLastHeight)
{
mLastWidth = textLabel.width;
mLastHeight = textLabel.height;
Rebuild();
}
}
}
/// <summary>
/// Allow scrolling of the text list.
/// </summary>
public void OnScroll (float val)
{
int sh = scrollHeight;
if (sh != 0)
{
val *= lineHeight;
scrollValue = mScroll - val / sh;
}
}
/// <summary>
/// Allow dragging of the text list.
/// </summary>
public void OnDrag (Vector2 delta)
{
int sh = scrollHeight;
if (sh != 0)
{
float val = delta.y / lineHeight;
scrollValue = mScroll + val / sh;
}
}
/// <summary>
/// Delegate function called when the scroll bar's value changes.
/// </summary>
void OnScrollBar ()
{
mScroll = UIScrollBar.current.value;
UpdateVisibleText();
}
/// <summary>
/// Add a new paragraph.
/// </summary>
public void Add (string text) { Add(text, true); }
/// <summary>
/// Add a new paragraph.
/// </summary>
protected void Add (string text, bool updateVisible)
{
Paragraph ce = null;
if (mParagraphs.size < paragraphHistory)
{
ce = new Paragraph();
}
else
{
ce = mParagraphs[0];
mParagraphs.RemoveAt(0);
}
ce.text = text;
mParagraphs.Add(ce);
Rebuild();
}
/// <summary>
/// Rebuild the visible text.
/// </summary>
protected void Rebuild ()
{
if (isValid)
{
// Although we could simply use UILabel.Wrap, it would mean setting the same data
// over and over every paragraph, which is not ideal. It's faster to only do it once
// and then do wrapping ourselves in the 'for' loop below.
textLabel.UpdateNGUIText();
NGUIText.rectHeight = 1000000;
mTotalLines = 0;
for (int i = 0; i < mParagraphs.size; ++i)
{
string final;
Paragraph p = mParagraphs.buffer[i];
NGUIText.WrapText(p.text, out final);
p.lines = final.Split('\n');
mTotalLines += p.lines.Length;
}
// Recalculate the total number of lines
mTotalLines = 0;
for (int i = 0, imax = mParagraphs.size; i < imax; ++i)
mTotalLines += mParagraphs.buffer[i].lines.Length;
// Update the bar's size
if (scrollBar != null)
{
UIScrollBar sb = scrollBar as UIScrollBar;
if (sb != null) sb.barSize = (mTotalLines == 0) ? 1f : 1f - (float)scrollHeight / mTotalLines;
}
// Update the visible text
UpdateVisibleText();
}
}
/// <summary>
/// Refill the text label based on what's currently visible.
/// </summary>
protected void UpdateVisibleText ()
{
if (isValid)
{
if (mTotalLines == 0)
{
textLabel.text = "";
return;
}
int maxLines = Mathf.FloorToInt((float)textLabel.height / lineHeight);
int sh = Mathf.Max(0, mTotalLines - maxLines);
int offset = Mathf.RoundToInt(mScroll * sh);
if (offset < 0) offset = 0;
StringBuilder final = new StringBuilder();
for (int i = 0, imax = mParagraphs.size; maxLines > 0 && i < imax; ++i)
{
Paragraph p = mParagraphs.buffer[i];
for (int b = 0, bmax = p.lines.Length; maxLines > 0 && b < bmax; ++b)
{
string s = p.lines[b];
if (offset > 0)
{
--offset;
}
else
{
if (final.Length > 0) final.Append("\n");
final.Append(s);
--maxLines;
}
}
}
textLabel.text = final.ToString();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UITextList.cs
|
C#
|
asf20
| 6,879
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Very simple sprite animation. Attach to a sprite and specify a common prefix such as "idle" and it will cycle through them.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(UISprite))]
[AddComponentMenu("NGUI/UI/Sprite Animation")]
public class UISpriteAnimation : MonoBehaviour
{
[HideInInspector][SerializeField] int mFPS = 30;
[HideInInspector][SerializeField] string mPrefix = "";
[HideInInspector][SerializeField] bool mLoop = true;
UISprite mSprite;
float mDelta = 0f;
int mIndex = 0;
bool mActive = true;
List<string> mSpriteNames = new List<string>();
/// <summary>
/// Number of frames in the animation.
/// </summary>
public int frames { get { return mSpriteNames.Count; } }
/// <summary>
/// Animation framerate.
/// </summary>
public int framesPerSecond { get { return mFPS; } set { mFPS = value; } }
/// <summary>
/// Set the name prefix used to filter sprites from the atlas.
/// </summary>
public string namePrefix { get { return mPrefix; } set { if (mPrefix != value) { mPrefix = value; RebuildSpriteList(); } } }
/// <summary>
/// Set the animation to be looping or not
/// </summary>
public bool loop { get { return mLoop; } set { mLoop = value; } }
/// <summary>
/// Returns is the animation is still playing or not
/// </summary>
public bool isPlaying { get { return mActive; } }
/// <summary>
/// Rebuild the sprite list first thing.
/// </summary>
void Start () { RebuildSpriteList(); }
/// <summary>
/// Advance the sprite animation process.
/// </summary>
void Update ()
{
if (mActive && mSpriteNames.Count > 1 && Application.isPlaying && mFPS > 0f)
{
mDelta += RealTime.deltaTime;
float rate = 1f / mFPS;
if (rate < mDelta)
{
mDelta = (rate > 0f) ? mDelta - rate : 0f;
if (++mIndex >= mSpriteNames.Count)
{
mIndex = 0;
mActive = loop;
}
if (mActive)
{
mSprite.spriteName = mSpriteNames[mIndex];
mSprite.MakePixelPerfect();
}
}
}
}
/// <summary>
/// Rebuild the sprite list after changing the sprite name.
/// </summary>
void RebuildSpriteList ()
{
if (mSprite == null) mSprite = GetComponent<UISprite>();
mSpriteNames.Clear();
if (mSprite != null && mSprite.atlas != null)
{
List<UISpriteData> sprites = mSprite.atlas.spriteList;
for (int i = 0, imax = sprites.Count; i < imax; ++i)
{
UISpriteData sprite = sprites[i];
if (string.IsNullOrEmpty(mPrefix) || sprite.name.StartsWith(mPrefix))
{
mSpriteNames.Add(sprite.name);
}
}
mSpriteNames.Sort();
}
}
/// <summary>
/// Reset the animation to frame 0 and activate it.
/// </summary>
public void Reset()
{
mActive = true;
mIndex = 0;
if (mSprite != null && mSpriteNames.Count > 0)
{
mSprite.spriteName = mSpriteNames[mIndex];
mSprite.MakePixelPerfect();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UISpriteAnimation.cs
|
C#
|
asf20
| 3,114
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// 2D Sprite is capable of drawing sprites added in Unity 4.3. When importing your textures,
/// import them as Sprites and you will be able to draw them with this widget.
/// If you provide a Packing Tag in your import settings, your sprites will get automatically
/// packed into an atlas for you, so creating an atlas beforehand is not necessary.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/NGUI Unity2D Sprite")]
public class UI2DSprite : UIWidget
{
[HideInInspector][SerializeField] UnityEngine.Sprite mSprite;
[HideInInspector][SerializeField] Material mMat;
[HideInInspector][SerializeField] Shader mShader;
/// <summary>
/// To be used with animations.
/// </summary>
public UnityEngine.Sprite nextSprite;
int mPMA = -1;
/// <summary>
/// UnityEngine.Sprite drawn by this widget.
/// </summary>
public UnityEngine.Sprite sprite2D
{
get
{
return mSprite;
}
set
{
if (mSprite != value)
{
RemoveFromPanel();
mSprite = value;
nextSprite = null;
MarkAsChanged();
}
}
}
/// <summary>
/// Material used by the widget.
/// </summary>
public override Material material
{
get
{
return mMat;
}
set
{
if (mMat != value)
{
RemoveFromPanel();
mMat = value;
mPMA = -1;
MarkAsChanged();
}
}
}
/// <summary>
/// Shader used by the texture when creating a dynamic material (when the texture was specified, but the material was not).
/// </summary>
public override Shader shader
{
get
{
if (mMat != null) return mMat.shader;
if (mShader == null) mShader = Shader.Find("Unlit/Transparent Colored");
return mShader;
}
set
{
if (mShader != value)
{
RemoveFromPanel();
mShader = value;
if (mMat == null)
{
mPMA = -1;
MarkAsChanged();
}
}
}
}
/// <summary>
/// Texture used by the UITexture. You can set it directly, without the need to specify a material.
/// </summary>
public override Texture mainTexture
{
get
{
if (mSprite != null) return mSprite.texture;
if (mMat != null) return mMat.mainTexture;
return null;
}
}
/// <summary>
/// Whether the texture is using a premultiplied alpha material.
/// </summary>
public bool premultipliedAlpha
{
get
{
if (mPMA == -1)
{
Shader sh = shader;
mPMA = (sh != null && sh.name.Contains("Premultiplied")) ? 1 : 0;
}
return (mPMA == 1);
}
}
/// <summary>
/// Widget's dimensions used for drawing. X = left, Y = bottom, Z = right, W = top.
/// This function automatically adds 1 pixel on the edge if the texture's dimensions are not even.
/// It's used to achieve pixel-perfect sprites even when an odd dimension widget happens to be centered.
/// </summary>
public override Vector4 drawingDimensions
{
get
{
Vector2 offset = pivotOffset;
float x0 = -offset.x * mWidth;
float y0 = -offset.y * mHeight;
float x1 = x0 + mWidth;
float y1 = y0 + mHeight;
int w = (mSprite != null) ? Mathf.RoundToInt(mSprite.textureRect.width) : mWidth;
int h = (mSprite != null) ? Mathf.RoundToInt(mSprite.textureRect.height) : mHeight;
if ((w & 1) != 0) x1 -= (1f / w) * mWidth;
if ((h & 1) != 0) y1 -= (1f / h) * mHeight;
return new Vector4(
mDrawRegion.x == 0f ? x0 : Mathf.Lerp(x0, x1, mDrawRegion.x),
mDrawRegion.y == 0f ? y0 : Mathf.Lerp(y0, y1, mDrawRegion.y),
mDrawRegion.z == 1f ? x1 : Mathf.Lerp(x0, x1, mDrawRegion.z),
mDrawRegion.w == 1f ? y1 : Mathf.Lerp(y0, y1, mDrawRegion.w));
}
}
/// <summary>
/// Texture rectangle.
/// </summary>
public Rect uvRect
{
get
{
Texture tex = mainTexture;
if (tex != null)
{
Rect rect = mSprite.textureRect;
rect.xMin /= tex.width;
rect.xMax /= tex.width;
rect.yMin /= tex.height;
rect.yMax /= tex.height;
return rect;
}
return new Rect(0f, 0f, 1f, 1f);
}
}
/// <summary>
/// Update the sprite in case it was animated.
/// </summary>
protected override void OnUpdate ()
{
if (nextSprite != null)
{
if (nextSprite != mSprite)
sprite2D = nextSprite;
nextSprite = null;
}
base.OnUpdate();
}
/// <summary>
/// Adjust the scale of the widget to make it pixel-perfect.
/// </summary>
public override void MakePixelPerfect ()
{
if (mSprite != null)
{
Rect rect = mSprite.textureRect;
int w = Mathf.RoundToInt(rect.width);
int h = Mathf.RoundToInt(rect.height);
if ((w & 1) == 1) ++w;
if ((h & 1) == 1) ++h;
width = w;
height = h;
}
base.MakePixelPerfect();
}
/// <summary>
/// Virtual function called by the UIPanel that fills the buffers.
/// </summary>
public override void OnFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Color colF = color;
colF.a = finalAlpha;
Color32 col = premultipliedAlpha ? NGUITools.ApplyPMA(colF) : colF;
Vector4 v = drawingDimensions;
Rect rect = uvRect;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
uvs.Add(new Vector2(rect.xMin, rect.yMin));
uvs.Add(new Vector2(rect.xMin, rect.yMax));
uvs.Add(new Vector2(rect.xMax, rect.yMax));
uvs.Add(new Vector2(rect.xMax, rect.yMin));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
}
#endif
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UI2DSprite.cs
|
C#
|
asf20
| 5,649
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
using UnityEngine;
/// <summary>
/// Small script that makes it easy to create looping 2D sprite animations.
/// </summary>
public class UI2DSpriteAnimation : MonoBehaviour
{
public int framerate = 20;
public bool ignoreTimeScale = true;
public UnityEngine.Sprite[] frames;
UnityEngine.SpriteRenderer mUnitySprite;
UI2DSprite mNguiSprite;
int mIndex = 0;
float mUpdate = 0f;
void Start ()
{
mUnitySprite = GetComponent<UnityEngine.SpriteRenderer>();
mNguiSprite = GetComponent<UI2DSprite>();
if (framerate > 0) mUpdate = (ignoreTimeScale ? RealTime.time : Time.time) + 1f / framerate;
}
void Update ()
{
if (framerate != 0 && frames != null && frames.Length > 0)
{
float time = ignoreTimeScale ? RealTime.time : Time.time;
if (mUpdate < time)
{
mUpdate = time;
mIndex = NGUIMath.RepeatIndex(framerate > 0 ? mIndex + 1 : mIndex - 1, frames.Length);
mUpdate = time + Mathf.Abs(1f / framerate);
if (mUnitySprite != null)
{
mUnitySprite.sprite = frames[mIndex];
}
else if (mNguiSprite != null)
{
mNguiSprite.nextSprite = frames[mIndex];
}
}
}
}
}
#endif
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UI2DSpriteAnimation.cs
|
C#
|
asf20
| 1,384
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This script can be used to anchor an object to the side or corner of the screen, panel, or a widget.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/Anchor")]
public class UIAnchor : MonoBehaviour
{
public enum Side
{
BottomLeft,
Left,
TopLeft,
Top,
TopRight,
Right,
BottomRight,
Bottom,
Center,
}
/// <summary>
/// Camera used to determine the anchor bounds. Set automatically if none was specified.
/// </summary>
public Camera uiCamera = null;
/// <summary>
/// Object used to determine the container's bounds. Overwrites the camera-based anchoring if the value was specified.
/// </summary>
public GameObject container = null;
/// <summary>
/// Side or corner to anchor to.
/// </summary>
public Side side = Side.Center;
/// <summary>
/// If set to 'true', UIAnchor will execute once, then will be disabled.
/// Screen size changes will still cause the anchor to update itself, even if it's disabled.
/// </summary>
public bool runOnlyOnce = true;
/// <summary>
/// Relative offset value, if any. For example "0.25" with 'side' set to Left, means 25% from the left side.
/// </summary>
public Vector2 relativeOffset = Vector2.zero;
/// <summary>
/// Pixel offset value if any. For example "10" in x will move the widget 10 pixels to the right
/// while "-10" in x is 10 pixels to the left based on the pixel values set in UIRoot.
/// </summary>
public Vector2 pixelOffset = Vector2.zero;
// Deprecated legacy functionality
[HideInInspector][SerializeField] UIWidget widgetContainer;
Transform mTrans;
Animation mAnim;
Rect mRect = new Rect();
UIRoot mRoot;
bool mStarted = false;
void Awake ()
{
mTrans = transform;
mAnim = animation;
UICamera.onScreenResize += ScreenSizeChanged;
}
void OnDestroy () { UICamera.onScreenResize -= ScreenSizeChanged; }
void ScreenSizeChanged () { if (mStarted && runOnlyOnce) Update(); }
/// <summary>
/// Automatically find the camera responsible for drawing the widgets under this object.
/// </summary>
void Start ()
{
if (container == null && widgetContainer != null)
{
container = widgetContainer.gameObject;
widgetContainer = null;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
mRoot = NGUITools.FindInParents<UIRoot>(gameObject);
if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
Update();
mStarted = true;
}
/// <summary>
/// Anchor the object to the appropriate point.
/// </summary>
void Update ()
{
if (mAnim != null && mAnim.enabled && mAnim.isPlaying) return;
bool useCamera = false;
UIWidget wc = (container == null) ? null : container.GetComponent<UIWidget>();
UIPanel pc = (container == null && wc == null) ? null : container.GetComponent<UIPanel>();
if (wc != null)
{
Bounds b = wc.CalculateBounds(container.transform.parent);
mRect.x = b.min.x;
mRect.y = b.min.y;
mRect.width = b.size.x;
mRect.height = b.size.y;
}
else if (pc != null)
{
if (pc.clipping == UIDrawCall.Clipping.None)
{
// Panel has no clipping -- just use the screen's dimensions
float ratio = (mRoot != null) ? (float)mRoot.activeHeight / Screen.height * 0.5f : 0.5f;
mRect.xMin = -Screen.width * ratio;
mRect.yMin = -Screen.height * ratio;
mRect.xMax = -mRect.xMin;
mRect.yMax = -mRect.yMin;
}
else
{
// Panel has clipping -- use it as the mRect
Vector4 pos = pc.finalClipRegion;
mRect.x = pos.x - (pos.z * 0.5f);
mRect.y = pos.y - (pos.w * 0.5f);
mRect.width = pos.z;
mRect.height = pos.w;
}
}
else if (container != null)
{
Transform root = container.transform.parent;
Bounds b = (root != null) ? NGUIMath.CalculateRelativeWidgetBounds(root, container.transform) :
NGUIMath.CalculateRelativeWidgetBounds(container.transform);
mRect.x = b.min.x;
mRect.y = b.min.y;
mRect.width = b.size.x;
mRect.height = b.size.y;
}
else if (uiCamera != null)
{
useCamera = true;
mRect = uiCamera.pixelRect;
}
else return;
float cx = (mRect.xMin + mRect.xMax) * 0.5f;
float cy = (mRect.yMin + mRect.yMax) * 0.5f;
Vector3 v = new Vector3(cx, cy, 0f);
if (side != Side.Center)
{
if (side == Side.Right || side == Side.TopRight || side == Side.BottomRight) v.x = mRect.xMax;
else if (side == Side.Top || side == Side.Center || side == Side.Bottom) v.x = cx;
else v.x = mRect.xMin;
if (side == Side.Top || side == Side.TopRight || side == Side.TopLeft) v.y = mRect.yMax;
else if (side == Side.Left || side == Side.Center || side == Side.Right) v.y = cy;
else v.y = mRect.yMin;
}
float width = mRect.width;
float height = mRect.height;
v.x += pixelOffset.x + relativeOffset.x * width;
v.y += pixelOffset.y + relativeOffset.y * height;
if (useCamera)
{
if (uiCamera.orthographic)
{
v.x = Mathf.Round(v.x);
v.y = Mathf.Round(v.y);
}
v.z = uiCamera.WorldToScreenPoint(mTrans.position).z;
v = uiCamera.ScreenToWorldPoint(v);
}
else
{
v.x = Mathf.Round(v.x);
v.y = Mathf.Round(v.y);
if (pc != null)
{
v = pc.cachedTransform.TransformPoint(v);
}
else if (container != null)
{
Transform t = container.transform.parent;
if (t != null) v = t.TransformPoint(v);
}
v.z = mTrans.position.z;
}
// Wrapped in an 'if' so the scene doesn't get marked as 'edited' every frame
if (mTrans.position != v) mTrans.position = v;
if (runOnlyOnce && Application.isPlaying) enabled = false;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/UI/UIAnchor.cs
|
C#
|
asf20
| 5,749
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Similar to UIButtonColor, but adds a 'disabled' state based on whether the collider is enabled or not.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Button")]
public class UIButton : UIButtonColor
{
/// <summary>
/// Current button that sent out the onClick event.
/// </summary>
static public UIButton current;
/// <summary>
/// Whether the button will highlight when you drag something over it.
/// </summary>
public bool dragHighlight = false;
/// <summary>
/// Name of the hover state sprite.
/// </summary>
public string hoverSprite;
/// <summary>
/// Name of the pressed sprite.
/// </summary>
public string pressedSprite;
/// <summary>
/// Name of the disabled sprite.
/// </summary>
public string disabledSprite;
/// <summary>
/// Whether the sprite changes will elicit a call to MakePixelPerfect() or not.
/// </summary>
public bool pixelSnap = false;
/// <summary>
/// Click event listener.
/// </summary>
public List<EventDelegate> onClick = new List<EventDelegate>();
// Cached value
[System.NonSerialized] string mNormalSprite;
[System.NonSerialized] UISprite mSprite;
/// <summary>
/// Whether the button should be enabled.
/// </summary>
public override bool isEnabled
{
get
{
if (!enabled) return false;
Collider col = collider;
if (col && col.enabled) return true;
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
Collider2D c2d = GetComponent<Collider2D>();
return (c2d && c2d.enabled);
#else
return false;
#endif
}
set
{
if (isEnabled != value)
{
Collider col = collider;
if (col != null)
{
col.enabled = value;
SetState(value ? State.Normal : State.Disabled, false);
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
else
{
Collider2D c2d = GetComponent<Collider2D>();
if (c2d != null)
{
c2d.enabled = value;
SetState(value ? State.Normal : State.Disabled, false);
}
else enabled = value;
}
#else
else enabled = value;
#endif
}
}
}
/// <summary>
/// Convenience function that changes the normal sprite.
/// </summary>
public string normalSprite
{
get
{
if (!mInitDone) OnInit();
return mNormalSprite;
}
set
{
if (mSprite != null && !string.IsNullOrEmpty(mNormalSprite) && mNormalSprite == mSprite.spriteName)
{
mNormalSprite = value;
SetSprite(value);
}
else
{
mNormalSprite = value;
if (mState == State.Normal) SetSprite(value);
}
}
}
/// <summary>
/// Cache the sprite we'll be working with.
/// </summary>
protected override void OnInit ()
{
base.OnInit();
mSprite = (mWidget as UISprite);
if (mSprite != null) mNormalSprite = mSprite.spriteName;
}
/// <summary>
/// Set the initial state.
/// </summary>
protected override void OnEnable ()
{
if (isEnabled)
{
if (mInitDone)
{
if (UICamera.currentScheme == UICamera.ControlScheme.Controller)
{
OnHover(UICamera.selectedObject == gameObject);
}
else if (UICamera.currentScheme == UICamera.ControlScheme.Mouse)
{
OnHover(UICamera.hoveredObject == gameObject);
}
else SetState(State.Normal, false);
}
}
else SetState(State.Disabled, true);
}
/// <summary>
/// Drag over state logic is a bit different for the button.
/// </summary>
protected override void OnDragOver ()
{
if (isEnabled && (dragHighlight || UICamera.currentTouch.pressed == gameObject))
base.OnDragOver();
}
/// <summary>
/// Drag out state logic is a bit different for the button.
/// </summary>
protected override void OnDragOut ()
{
if (isEnabled && (dragHighlight || UICamera.currentTouch.pressed == gameObject))
base.OnDragOut();
}
/// <summary>
/// Call the listener function.
/// </summary>
protected virtual void OnClick ()
{
if (current == null && isEnabled)
{
current = this;
EventDelegate.Execute(onClick);
current = null;
}
}
/// <summary>
/// Change the visual state.
/// </summary>
public override void SetState (State state, bool immediate)
{
base.SetState(state, immediate);
switch (state)
{
case State.Normal: SetSprite(mNormalSprite); break;
case State.Hover: SetSprite(hoverSprite); break;
case State.Pressed: SetSprite(pressedSprite); break;
case State.Disabled: SetSprite(disabledSprite); break;
}
}
/// <summary>
/// Convenience function that changes the sprite.
/// </summary>
protected void SetSprite (string sp)
{
if (mSprite != null && !string.IsNullOrEmpty(sp) && mSprite.spriteName != sp)
{
mSprite.spriteName = sp;
if (pixelSnap) mSprite.MakePixelPerfect();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIButton.cs
|
C#
|
asf20
| 4,918
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Attaching this script to an object will let you trigger remote functions using NGUI events.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Event Trigger")]
public class UIEventTrigger : MonoBehaviour
{
static public UIEventTrigger current;
public List<EventDelegate> onHoverOver = new List<EventDelegate>();
public List<EventDelegate> onHoverOut = new List<EventDelegate>();
public List<EventDelegate> onPress = new List<EventDelegate>();
public List<EventDelegate> onRelease = new List<EventDelegate>();
public List<EventDelegate> onSelect = new List<EventDelegate>();
public List<EventDelegate> onDeselect = new List<EventDelegate>();
public List<EventDelegate> onClick = new List<EventDelegate>();
public List<EventDelegate> onDoubleClick = new List<EventDelegate>();
public List<EventDelegate> onDragOver = new List<EventDelegate>();
public List<EventDelegate> onDragOut = new List<EventDelegate>();
void OnHover (bool isOver)
{
if (current != null) return;
current = this;
if (isOver) EventDelegate.Execute(onHoverOver);
else EventDelegate.Execute(onHoverOut);
current = null;
}
void OnPress (bool pressed)
{
if (current != null) return;
current = this;
if (pressed) EventDelegate.Execute(onPress);
else EventDelegate.Execute(onRelease);
current = null;
}
void OnSelect (bool selected)
{
if (current != null) return;
current = this;
if (selected) EventDelegate.Execute(onSelect);
else EventDelegate.Execute(onDeselect);
current = null;
}
void OnClick ()
{
if (current != null) return;
current = this;
EventDelegate.Execute(onClick);
current = null;
}
void OnDoubleClick ()
{
if (current != null) return;
current = this;
EventDelegate.Execute(onDoubleClick);
current = null;
}
void OnDragOver (GameObject go)
{
if (current != null) return;
current = this;
EventDelegate.Execute(onDragOver);
current = null;
}
void OnDragOut (GameObject go)
{
if (current != null) return;
current = this;
EventDelegate.Execute(onDragOut);
current = null;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIEventTrigger.cs
|
C#
|
asf20
| 2,308
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This script, when attached to a panel turns it into a scroll view.
/// You can then attach UIDragScrollView to colliders within to make it draggable.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(UIPanel))]
[AddComponentMenu("NGUI/Interaction/Scroll View")]
public class UIScrollView : MonoBehaviour
{
static public BetterList<UIScrollView> list = new BetterList<UIScrollView>();
public enum Movement
{
Horizontal,
Vertical,
Unrestricted,
Custom,
}
public enum DragEffect
{
None,
Momentum,
MomentumAndSpring,
}
public enum ShowCondition
{
Always,
OnlyIfNeeded,
WhenDragging,
}
public delegate void OnDragFinished ();
/// <summary>
/// Type of movement allowed by the scroll view.
/// </summary>
public Movement movement = Movement.Horizontal;
/// <summary>
/// Effect to apply when dragging.
/// </summary>
public DragEffect dragEffect = DragEffect.MomentumAndSpring;
/// <summary>
/// Whether the dragging will be restricted to be within the scroll view's bounds.
/// </summary>
public bool restrictWithinPanel = true;
/// <summary>
/// Whether dragging will be disabled if the contents fit.
/// </summary>
public bool disableDragIfFits = false;
/// <summary>
/// Whether the drag operation will be started smoothly, or if if it will be precise (but will have a noticeable "jump").
/// </summary>
public bool smoothDragStart = true;
/// <summary>
/// Whether to use iOS drag emulation, where the content only drags at half the speed of the touch/mouse movement when the content edge is within the clipping area.
/// </summary>
public bool iOSDragEmulation = true;
/// <summary>
/// Effect the scroll wheel will have on the momentum.
/// </summary>
public float scrollWheelFactor = 0.25f;
/// <summary>
/// How much momentum gets applied when the press is released after dragging.
/// </summary>
public float momentumAmount = 35f;
/// <summary>
/// Horizontal scrollbar used for visualization.
/// </summary>
public UIProgressBar horizontalScrollBar;
/// <summary>
/// Vertical scrollbar used for visualization.
/// </summary>
public UIProgressBar verticalScrollBar;
/// <summary>
/// Condition that must be met for the scroll bars to become visible.
/// </summary>
public ShowCondition showScrollBars = ShowCondition.OnlyIfNeeded;
/// <summary>
/// Custom movement, if the 'movement' field is set to 'Custom'.
/// </summary>
public Vector2 customMovement = new Vector2(1f, 0f);
/// <summary>
/// Content's pivot point -- where it originates from by default.
/// </summary>
public UIWidget.Pivot contentPivot = UIWidget.Pivot.TopLeft;
/// <summary>
/// Event callback to trigger when the drag process finished. Can be used for additional effects, such as centering on some object.
/// </summary>
public OnDragFinished onDragFinished;
// Deprecated functionality. Use 'movement' instead.
[HideInInspector][SerializeField] Vector3 scale = new Vector3(1f, 0f, 0f);
// Deprecated functionality. Use 'contentPivot' instead.
[SerializeField][HideInInspector] Vector2 relativePositionOnReset = Vector2.zero;
protected Transform mTrans;
protected UIPanel mPanel;
protected Plane mPlane;
protected Vector3 mLastPos;
protected bool mPressed = false;
protected Vector3 mMomentum = Vector3.zero;
protected float mScroll = 0f;
protected Bounds mBounds;
protected bool mCalculatedBounds = false;
protected bool mShouldMove = false;
protected bool mIgnoreCallbacks = false;
protected int mDragID = -10;
protected Vector2 mDragStartOffset = Vector2.zero;
protected bool mDragStarted = false;
/// <summary>
/// Panel that's being dragged.
/// </summary>
public UIPanel panel { get { return mPanel; } }
/// <summary>
/// Whether the scroll view is being dragged.
/// </summary>
public bool isDragging { get { return mPressed && mDragStarted; } }
/// <summary>
/// Calculate the bounds used by the widgets.
/// </summary>
public virtual Bounds bounds
{
get
{
if (!mCalculatedBounds)
{
mCalculatedBounds = true;
mTrans = transform;
mBounds = NGUIMath.CalculateRelativeWidgetBounds(mTrans, mTrans);
}
return mBounds;
}
}
/// <summary>
/// Whether the scroll view can move horizontally.
/// </summary>
public bool canMoveHorizontally
{
get
{
return movement == Movement.Horizontal ||
movement == Movement.Unrestricted ||
(movement == Movement.Custom && customMovement.x != 0f);
}
}
/// <summary>
/// Whether the scroll view can move vertically.
/// </summary>
public bool canMoveVertically
{
get
{
return movement == Movement.Vertical ||
movement == Movement.Unrestricted ||
(movement == Movement.Custom && customMovement.y != 0f);
}
}
/// <summary>
/// Whether the scroll view should be able to move horizontally (contents don't fit).
/// </summary>
public virtual bool shouldMoveHorizontally
{
get
{
float size = bounds.size.x;
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip) size += mPanel.clipSoftness.x * 2f;
return Mathf.RoundToInt(size - mPanel.width) > 0;
}
}
/// <summary>
/// Whether the scroll view should be able to move vertically (contents don't fit).
/// </summary>
public virtual bool shouldMoveVertically
{
get
{
float size = bounds.size.y;
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip) size += mPanel.clipSoftness.y * 2f;
return Mathf.RoundToInt(size - mPanel.height) > 0;
}
}
/// <summary>
/// Whether the contents of the scroll view should actually be draggable depends on whether they currently fit or not.
/// </summary>
protected virtual bool shouldMove
{
get
{
if (!disableDragIfFits) return true;
if (mPanel == null) mPanel = GetComponent<UIPanel>();
Vector4 clip = mPanel.finalClipRegion;
Bounds b = bounds;
float hx = (clip.z == 0f) ? Screen.width : clip.z * 0.5f;
float hy = (clip.w == 0f) ? Screen.height : clip.w * 0.5f;
if (canMoveHorizontally)
{
if (b.min.x < clip.x - hx) return true;
if (b.max.x > clip.x + hx) return true;
}
if (canMoveVertically)
{
if (b.min.y < clip.y - hy) return true;
if (b.max.y > clip.y + hy) return true;
}
return false;
}
}
/// <summary>
/// Current momentum, exposed just in case it's needed.
/// </summary>
public Vector3 currentMomentum { get { return mMomentum; } set { mMomentum = value; mShouldMove = true; } }
/// <summary>
/// Cache the transform and the panel.
/// </summary>
void Awake ()
{
mTrans = transform;
mPanel = GetComponent<UIPanel>();
if (mPanel.clipping == UIDrawCall.Clipping.None)
mPanel.clipping = UIDrawCall.Clipping.ConstrainButDontClip;
// Auto-upgrade
if (movement != Movement.Custom && scale.sqrMagnitude > 0.001f)
{
if (scale.x == 1f && scale.y == 0f)
{
movement = Movement.Horizontal;
}
else if (scale.x == 0f && scale.y == 1f)
{
movement = Movement.Vertical;
}
else if (scale.x == 1f && scale.y == 1f)
{
movement = Movement.Unrestricted;
}
else
{
movement = Movement.Custom;
customMovement.x = scale.x;
customMovement.y = scale.y;
}
scale = Vector3.zero;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
// Auto-upgrade
if (contentPivot == UIWidget.Pivot.TopLeft && relativePositionOnReset != Vector2.zero)
{
contentPivot = NGUIMath.GetPivot(new Vector2(relativePositionOnReset.x, 1f - relativePositionOnReset.y));
relativePositionOnReset = Vector2.zero;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
}
void OnEnable () { list.Add(this); }
void OnDisable () { list.Remove(this); }
/// <summary>
/// Set the initial drag value and register the listener delegates.
/// </summary>
protected virtual void Start ()
{
//UpdatePosition();
if (Application.isPlaying)
{
if (horizontalScrollBar != null)
{
EventDelegate.Add(horizontalScrollBar.onChange, OnScrollBar);
horizontalScrollBar.alpha = ((showScrollBars == ShowCondition.Always) || shouldMoveHorizontally) ? 1f : 0f;
}
if (verticalScrollBar != null)
{
EventDelegate.Add(verticalScrollBar.onChange, OnScrollBar);
verticalScrollBar.alpha = ((showScrollBars == ShowCondition.Always) || shouldMoveVertically) ? 1f : 0f;
}
}
}
/// <summary>
/// Restrict the scroll view's contents to be within the scroll view's bounds.
/// </summary>
public bool RestrictWithinBounds (bool instant) { return RestrictWithinBounds(instant, true, true); }
/// <summary>
/// Restrict the scroll view's contents to be within the scroll view's bounds.
/// </summary>
public bool RestrictWithinBounds (bool instant, bool horizontal, bool vertical)
{
Bounds b = bounds;
Vector3 constraint = mPanel.CalculateConstrainOffset(b.min, b.max);
if (!horizontal) constraint.x = 0f;
if (!vertical) constraint.y = 0f;
if (constraint.sqrMagnitude > 1f)
{
if (!instant && dragEffect == DragEffect.MomentumAndSpring)
{
// Spring back into place
Vector3 pos = mTrans.localPosition + constraint;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
SpringPanel.Begin(mPanel.gameObject, pos, 13f);
}
else
{
// Jump back into place
MoveRelative(constraint);
mMomentum = Vector3.zero;
mScroll = 0f;
}
return true;
}
return false;
}
/// <summary>
/// Disable the spring movement.
/// </summary>
public void DisableSpring ()
{
SpringPanel sp = GetComponent<SpringPanel>();
if (sp != null) sp.enabled = false;
}
/// <summary>
/// Update the values of the associated scroll bars.
/// </summary>
public void UpdateScrollbars () { UpdateScrollbars(true); }
/// <summary>
/// Update the values of the associated scroll bars.
/// </summary>
public virtual void UpdateScrollbars (bool recalculateBounds)
{
if (mPanel == null) return;
if (horizontalScrollBar != null || verticalScrollBar != null)
{
if (recalculateBounds)
{
mCalculatedBounds = false;
mShouldMove = shouldMove;
}
Bounds b = bounds;
Vector2 bmin = b.min;
Vector2 bmax = b.max;
if (horizontalScrollBar != null && bmax.x > bmin.x)
{
Vector4 clip = mPanel.finalClipRegion;
int intViewSize = Mathf.RoundToInt(clip.z);
if ((intViewSize & 1) != 0) intViewSize -= 1;
float halfViewSize = intViewSize * 0.5f;
halfViewSize = Mathf.Round(halfViewSize);
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip)
halfViewSize -= mPanel.clipSoftness.x;
float contentSize = bmax.x - bmin.x;
float viewSize = halfViewSize * 2f;
float contentMin = bmin.x;
float contentMax = bmax.x;
float viewMin = clip.x - halfViewSize;
float viewMax = clip.x + halfViewSize;
contentMin = viewMin - contentMin;
contentMax = contentMax - viewMax;
UpdateScrollbars(horizontalScrollBar, contentMin, contentMax, contentSize, viewSize, false);
}
if (verticalScrollBar != null && bmax.y > bmin.y)
{
Vector4 clip = mPanel.finalClipRegion;
int intViewSize = Mathf.RoundToInt(clip.w);
if ((intViewSize & 1) != 0) intViewSize -= 1;
float halfViewSize = intViewSize * 0.5f;
halfViewSize = Mathf.Round(halfViewSize);
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip)
halfViewSize -= mPanel.clipSoftness.y;
float contentSize = bmax.y - bmin.y;
float viewSize = halfViewSize * 2f;
float contentMin = bmin.y;
float contentMax = bmax.y;
float viewMin = clip.y - halfViewSize;
float viewMax = clip.y + halfViewSize;
contentMin = viewMin - contentMin;
contentMax = contentMax - viewMax;
UpdateScrollbars(verticalScrollBar, contentMin, contentMax, contentSize, viewSize, true);
}
}
else if (recalculateBounds)
{
mCalculatedBounds = false;
}
}
/// <summary>
/// Helper function used in UpdateScrollbars(float) function above.
/// </summary>
protected void UpdateScrollbars (UIProgressBar slider, float contentMin, float contentMax, float contentSize, float viewSize, bool inverted)
{
if (slider == null) return;
mIgnoreCallbacks = true;
{
float contentPadding;
if (viewSize < contentSize)
{
contentMin = Mathf.Clamp01(contentMin / contentSize);
contentMax = Mathf.Clamp01(contentMax / contentSize);
contentPadding = contentMin + contentMax;
slider.value = inverted ? ((contentPadding > 0.001f) ? 1f - contentMin / contentPadding : 0f) :
((contentPadding > 0.001f) ? contentMin / contentPadding : 1f);
}
else
{
contentMin = Mathf.Clamp01(-contentMin / contentSize);
contentMax = Mathf.Clamp01(-contentMax / contentSize);
contentPadding = contentMin + contentMax;
slider.value = inverted ? ((contentPadding > 0.001f) ? 1f - contentMin / contentPadding : 0f) :
((contentPadding > 0.001f) ? contentMin / contentPadding : 1f);
if (contentSize > 0)
{
contentMin = Mathf.Clamp01(contentMin / contentSize);
contentMax = Mathf.Clamp01(contentMax / contentSize);
contentPadding = contentMin + contentMax;
}
}
UIScrollBar sb = slider as UIScrollBar;
if (sb != null) sb.barSize = 1f - contentPadding;
}
mIgnoreCallbacks = false;
}
/// <summary>
/// Changes the drag amount of the scroll view to the specified 0-1 range values.
/// (0, 0) is the top-left corner, (1, 1) is the bottom-right.
/// </summary>
public virtual void SetDragAmount (float x, float y, bool updateScrollbars)
{
if (mPanel == null) mPanel = GetComponent<UIPanel>();
DisableSpring();
Bounds b = bounds;
if (b.min.x == b.max.x || b.min.y == b.max.y) return;
Vector4 clip = mPanel.finalClipRegion;
float hx = clip.z * 0.5f;
float hy = clip.w * 0.5f;
float left = b.min.x + hx;
float right = b.max.x - hx;
float bottom = b.min.y + hy;
float top = b.max.y - hy;
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip)
{
left -= mPanel.clipSoftness.x;
right += mPanel.clipSoftness.x;
bottom -= mPanel.clipSoftness.y;
top += mPanel.clipSoftness.y;
}
// Calculate the offset based on the scroll value
float ox = Mathf.Lerp(left, right, x);
float oy = Mathf.Lerp(top, bottom, y);
// Update the position
if (!updateScrollbars)
{
Vector3 pos = mTrans.localPosition;
if (canMoveHorizontally) pos.x += clip.x - ox;
if (canMoveVertically) pos.y += clip.y - oy;
mTrans.localPosition = pos;
}
if (canMoveHorizontally) clip.x = ox;
if (canMoveVertically) clip.y = oy;
// Update the clipping offset
Vector4 cr = mPanel.baseClipRegion;
mPanel.clipOffset = new Vector2(clip.x - cr.x, clip.y - cr.y);
// Update the scrollbars, reflecting this change
if (updateScrollbars) UpdateScrollbars(mDragID == -10);
}
/// <summary>
/// Reset the scroll view's position to the top-left corner.
/// It's recommended to call this function before AND after you re-populate the scroll view's contents (ex: switching window tabs).
/// Another option is to populate the scroll view's contents, reset its position, then call this function to reposition the clipping.
/// </summary>
[ContextMenu("Reset Clipping Position")]
public void ResetPosition()
{
if (NGUITools.GetActive(this))
{
// Invalidate the bounds
mCalculatedBounds = false;
Vector2 pv = NGUIMath.GetPivotOffset(contentPivot);
// First move the position back to where it would be if the scroll bars got reset to zero
SetDragAmount(pv.x, 1f - pv.y, false);
// Next move the clipping area back and update the scroll bars
SetDragAmount(pv.x, 1f - pv.y, true);
}
}
/// <summary>
/// Call this function after you adjust the scroll view's bounds if you want it to maintain the current scrolled position
/// </summary>
public void UpdatePosition ()
{
if (!mIgnoreCallbacks && (horizontalScrollBar != null || verticalScrollBar != null))
{
mIgnoreCallbacks = true;
mCalculatedBounds = false;
Vector2 pv = NGUIMath.GetPivotOffset(contentPivot);
float x = (horizontalScrollBar != null) ? horizontalScrollBar.value : pv.x;
float y = (verticalScrollBar != null) ? verticalScrollBar.value : 1f - pv.y;
SetDragAmount(x, y, false);
UpdateScrollbars(true);
mIgnoreCallbacks = false;
}
}
/// <summary>
/// Triggered by the scroll bars when they change.
/// </summary>
public void OnScrollBar ()
{
if (!mIgnoreCallbacks)
{
mIgnoreCallbacks = true;
float x = (horizontalScrollBar != null) ? horizontalScrollBar.value : 0f;
float y = (verticalScrollBar != null) ? verticalScrollBar.value : 0f;
SetDragAmount(x, y, false);
mIgnoreCallbacks = false;
}
}
/// <summary>
/// Move the scroll view by the specified amount.
/// </summary>
public virtual void MoveRelative (Vector3 relative)
{
mTrans.localPosition += relative;
Vector2 co = mPanel.clipOffset;
co.x -= relative.x;
co.y -= relative.y;
mPanel.clipOffset = co;
// Update the scroll bars
UpdateScrollbars(false);
}
/// <summary>
/// Move the scroll view by the specified amount.
/// </summary>
public void MoveAbsolute (Vector3 absolute)
{
Vector3 a = mTrans.InverseTransformPoint(absolute);
Vector3 b = mTrans.InverseTransformPoint(Vector3.zero);
MoveRelative(a - b);
}
/// <summary>
/// Create a plane on which we will be performing the dragging.
/// </summary>
public void Press (bool pressed)
{
if (smoothDragStart && pressed)
{
mDragStarted = false;
mDragStartOffset = Vector2.zero;
}
if (enabled && NGUITools.GetActive(gameObject))
{
if (!pressed && mDragID == UICamera.currentTouchID) mDragID = -10;
mCalculatedBounds = false;
mShouldMove = shouldMove;
if (!mShouldMove) return;
mPressed = pressed;
if (pressed)
{
// Remove all momentum on press
mMomentum = Vector3.zero;
mScroll = 0f;
// Disable the spring movement
DisableSpring();
// Remember the hit position
mLastPos = UICamera.lastHit.point;
// Create the plane to drag along
mPlane = new Plane(mTrans.rotation * Vector3.back, mLastPos);
// Ensure that we're working with whole numbers, keeping everything pixel-perfect
Vector2 co = mPanel.clipOffset;
co.x = Mathf.Round(co.x);
co.y = Mathf.Round(co.y);
mPanel.clipOffset = co;
Vector3 v = mTrans.localPosition;
v.x = Mathf.Round(v.x);
v.y = Mathf.Round(v.y);
mTrans.localPosition = v;
}
else
{
if (restrictWithinPanel && mPanel.clipping != UIDrawCall.Clipping.None && dragEffect == DragEffect.MomentumAndSpring)
RestrictWithinBounds(false, canMoveHorizontally, canMoveVertically);
if (onDragFinished != null)
onDragFinished();
}
}
}
/// <summary>
/// Drag the object along the plane.
/// </summary>
public void Drag ()
{
if (enabled && NGUITools.GetActive(gameObject) && mShouldMove)
{
if (mDragID == -10) mDragID = UICamera.currentTouchID;
UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;
// Prevents the drag "jump". Contributed by 'mixd' from the Tasharen forums.
if (smoothDragStart && !mDragStarted)
{
mDragStarted = true;
mDragStartOffset = UICamera.currentTouch.totalDelta;
}
Ray ray = smoothDragStart ?
UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos - mDragStartOffset) :
UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos);
float dist = 0f;
if (mPlane.Raycast(ray, out dist))
{
Vector3 currentPos = ray.GetPoint(dist);
Vector3 offset = currentPos - mLastPos;
mLastPos = currentPos;
if (offset.x != 0f || offset.y != 0f || offset.z != 0f)
{
offset = mTrans.InverseTransformDirection(offset);
if (movement == Movement.Horizontal)
{
offset.y = 0f;
offset.z = 0f;
}
else if (movement == Movement.Vertical)
{
offset.x = 0f;
offset.z = 0f;
}
else if (movement == Movement.Unrestricted)
{
offset.z = 0f;
}
else
{
offset.Scale((Vector3)customMovement);
}
offset = mTrans.TransformDirection(offset);
}
// Adjust the momentum
mMomentum = Vector3.Lerp(mMomentum, mMomentum + offset * (0.01f * momentumAmount), 0.67f);
// Move the scroll view
if (!iOSDragEmulation || dragEffect != DragEffect.MomentumAndSpring)
{
MoveAbsolute(offset);
}
else
{
Vector3 constraint = mPanel.CalculateConstrainOffset(bounds.min, bounds.max);
if (constraint.magnitude > 1f)
{
MoveAbsolute(offset * 0.5f);
mMomentum *= 0.5f;
}
else
{
MoveAbsolute(offset);
}
}
// We want to constrain the UI to be within bounds
if (restrictWithinPanel &&
mPanel.clipping != UIDrawCall.Clipping.None &&
dragEffect != DragEffect.MomentumAndSpring)
{
RestrictWithinBounds(true, canMoveHorizontally, canMoveVertically);
}
}
}
}
/// <summary>
/// If the object should support the scroll wheel, do it.
/// </summary>
public void Scroll (float delta)
{
if (enabled && NGUITools.GetActive(gameObject) && scrollWheelFactor != 0f)
{
DisableSpring();
mShouldMove = shouldMove;
if (Mathf.Sign(mScroll) != Mathf.Sign(delta)) mScroll = 0f;
mScroll += delta * scrollWheelFactor;
}
}
/// <summary>
/// Apply the dragging momentum.
/// </summary>
void LateUpdate ()
{
if (!Application.isPlaying) return;
float delta = RealTime.deltaTime;
// Fade the scroll bars if needed
if (showScrollBars != ShowCondition.Always && (verticalScrollBar || horizontalScrollBar))
{
bool vertical = false;
bool horizontal = false;
if (showScrollBars != ShowCondition.WhenDragging || mDragID != -10 || mMomentum.magnitude > 0.01f)
{
vertical = shouldMoveVertically;
horizontal = shouldMoveHorizontally;
}
if (verticalScrollBar)
{
float alpha = verticalScrollBar.alpha;
alpha += vertical ? delta * 6f : -delta * 3f;
alpha = Mathf.Clamp01(alpha);
if (verticalScrollBar.alpha != alpha) verticalScrollBar.alpha = alpha;
}
if (horizontalScrollBar)
{
float alpha = horizontalScrollBar.alpha;
alpha += horizontal ? delta * 6f : -delta * 3f;
alpha = Mathf.Clamp01(alpha);
if (horizontalScrollBar.alpha != alpha) horizontalScrollBar.alpha = alpha;
}
}
// Apply momentum
if (mShouldMove && !mPressed)
{
if (movement == Movement.Horizontal)
{
mMomentum -= mTrans.TransformDirection(new Vector3(mScroll * 0.05f, 0f, 0f));
}
else if (movement == Movement.Vertical)
{
mMomentum -= mTrans.TransformDirection(new Vector3(0f, mScroll * 0.05f, 0f));
}
else if (movement == Movement.Unrestricted)
{
mMomentum -= mTrans.TransformDirection(new Vector3(mScroll * 0.05f, mScroll * 0.05f, 0f));
}
else
{
mMomentum -= mTrans.TransformDirection(new Vector3(
mScroll * customMovement.x * 0.05f,
mScroll * customMovement.y * 0.05f, 0f));
}
if (mMomentum.magnitude > 0.0001f)
{
mScroll = NGUIMath.SpringLerp(mScroll, 0f, 20f, delta);
// Move the scroll view
Vector3 offset = NGUIMath.SpringDampen(ref mMomentum, 9f, delta);
MoveAbsolute(offset);
// Restrict the contents to be within the scroll view's bounds
if (restrictWithinPanel && mPanel.clipping != UIDrawCall.Clipping.None)
RestrictWithinBounds(false, canMoveHorizontally, canMoveVertically);
if (mMomentum.magnitude < 0.0001f && onDragFinished != null)
onDragFinished();
return;
}
else
{
mScroll = 0f;
mMomentum = Vector3.zero;
}
}
else mScroll = 0f;
// Dampen the momentum
NGUIMath.SpringDampen(ref mMomentum, 9f, delta);
}
#if UNITY_EDITOR
/// <summary>
/// Draw a visible orange outline of the bounds.
/// </summary>
void OnDrawGizmos ()
{
if (mPanel != null)
{
if (!Application.isPlaying) mCalculatedBounds = false;
Bounds b = bounds;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.color = new Color(1f, 0.4f, 0f);
Gizmos.DrawWireCube(new Vector3(b.center.x, b.center.y, b.min.z), new Vector3(b.size.x, b.size.y, 0f));
}
}
#endif
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIScrollView.cs
|
C#
|
asf20
| 24,341
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections;
/// <summary>
/// Allows dragging of the specified scroll view by mouse or touch.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Drag Scroll View")]
public class UIDragScrollView : MonoBehaviour
{
/// <summary>
/// Reference to the scroll view that will be dragged by the script.
/// </summary>
public UIScrollView scrollView;
// Legacy functionality, kept for backwards compatibility. Use 'scrollView' instead.
[HideInInspector][SerializeField] UIScrollView draggablePanel;
Transform mTrans;
UIScrollView mScroll;
bool mAutoFind = false;
bool mStarted = false;
/// <summary>
/// Automatically find the scroll view if possible.
/// </summary>
void OnEnable ()
{
mTrans = transform;
// Auto-upgrade
if (scrollView == null && draggablePanel != null)
{
scrollView = draggablePanel;
draggablePanel = null;
}
if (mStarted && (mAutoFind || mScroll == null))
FindScrollView();
}
/// <summary>
/// Find the scroll view.
/// </summary>
void Start ()
{
mStarted = true;
FindScrollView();
}
/// <summary>
/// Find the scroll view to work with.
/// </summary>
void FindScrollView ()
{
// If the scroll view is on a parent, don't try to remember it (as we want it to be dynamic in case of re-parenting)
UIScrollView sv = NGUITools.FindInParents<UIScrollView>(mTrans);
if (scrollView == null)
{
scrollView = sv;
mAutoFind = true;
}
else if (scrollView == sv)
{
mAutoFind = true;
}
mScroll = scrollView;
}
/// <summary>
/// Create a plane on which we will be performing the dragging.
/// </summary>
void OnPress (bool pressed)
{
// If the scroll view has been set manually, don't try to find it again
if (mAutoFind && mScroll != scrollView)
{
mScroll = scrollView;
mAutoFind = false;
}
if (scrollView && enabled && NGUITools.GetActive(gameObject))
{
scrollView.Press(pressed);
if (!pressed && mAutoFind)
{
scrollView = NGUITools.FindInParents<UIScrollView>(mTrans);
mScroll = scrollView;
}
}
}
/// <summary>
/// Drag the object along the plane.
/// </summary>
void OnDrag (Vector2 delta)
{
if (scrollView && NGUITools.GetActive(this))
scrollView.Drag();
}
/// <summary>
/// If the object should support the scroll wheel, do it.
/// </summary>
void OnScroll (float delta)
{
if (scrollView && NGUITools.GetActive(this))
scrollView.Scroll(delta);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIDragScrollView.cs
|
C#
|
asf20
| 2,639
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections;
/// <summary>
/// Widget container is a generic type class that acts like a non-resizeable widget when selecting things in the scene view.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Widget Container")]
public class UIWidgetContainer : MonoBehaviour { }
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIWidgetContainer.cs
|
C#
|
asf20
| 492
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Allows dragging of the camera object and restricts camera's movement to be within bounds of the area created by the rootForBounds colliders.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/Drag Camera")]
public class UIDragCamera : MonoBehaviour
{
/// <summary>
/// Target object that will be dragged.
/// </summary>
public UIDraggableCamera draggableCamera;
/// <summary>
/// Automatically find the draggable camera if possible.
/// </summary>
void Awake ()
{
if (draggableCamera == null)
{
draggableCamera = NGUITools.FindInParents<UIDraggableCamera>(gameObject);
}
}
/// <summary>
/// Forward the press event to the draggable camera.
/// </summary>
void OnPress (bool isPressed)
{
if (enabled && NGUITools.GetActive(gameObject) && draggableCamera != null)
{
draggableCamera.Press(isPressed);
}
}
/// <summary>
/// Forward the drag event to the draggable camera.
/// </summary>
void OnDrag (Vector2 delta)
{
if (enabled && NGUITools.GetActive(gameObject) && draggableCamera != null)
{
draggableCamera.Drag(delta);
}
}
/// <summary>
/// Forward the scroll event to the draggable camera.
/// </summary>
void OnScroll (float delta)
{
if (enabled && NGUITools.GetActive(gameObject) && draggableCamera != null)
{
draggableCamera.Scroll(delta);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIDragCamera.cs
|
C#
|
asf20
| 1,566
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Simple example script of how a button can be colored when the mouse hovers over it or it gets pressed.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/Button Color")]
public class UIButtonColor : UIWidgetContainer
{
public enum State
{
Normal,
Hover,
Pressed,
Disabled,
}
/// <summary>
/// Target with a widget, renderer, or light that will have its color tweened.
/// </summary>
public GameObject tweenTarget;
/// <summary>
/// Color to apply on hover event (mouse only).
/// </summary>
public Color hover = new Color(225f / 255f, 200f / 255f, 150f / 255f, 1f);
/// <summary>
/// Color to apply on the pressed event.
/// </summary>
public Color pressed = new Color(183f / 255f, 163f / 255f, 123f / 255f, 1f);
/// <summary>
/// Color that will be applied when the button is disabled.
/// </summary>
public Color disabledColor = Color.grey;
/// <summary>
/// Duration of the tween process.
/// </summary>
public float duration = 0.2f;
protected Color mColor;
protected bool mInitDone = false;
protected UIWidget mWidget;
protected State mState = State.Normal;
/// <summary>
/// Button's current state.
/// </summary>
public State state { get { return mState; } set { SetState(value, false); } }
/// <summary>
/// UIButtonColor's default (starting) color. It's useful to be able to change it, just in case.
/// </summary>
public Color defaultColor
{
get
{
#if UNITY_EDITOR
if (!Application.isPlaying) return Color.white;
#endif
if (!mInitDone) OnInit();
return mColor;
}
set
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (!mInitDone) OnInit();
mColor = value;
}
}
/// <summary>
/// Whether the script should be active or not.
/// </summary>
public virtual bool isEnabled { get { return enabled; } set { enabled = value; } }
void Awake () { if (!mInitDone) OnInit(); }
void Start () { if (!isEnabled) SetState(State.Disabled, true); }
protected virtual void OnInit ()
{
mInitDone = true;
if (tweenTarget == null) tweenTarget = gameObject;
mWidget = tweenTarget.GetComponent<UIWidget>();
if (mWidget != null)
{
mColor = mWidget.color;
}
else
{
Renderer ren = tweenTarget.renderer;
if (ren != null)
{
mColor = Application.isPlaying ? ren.material.color : ren.sharedMaterial.color;
}
else
{
Light lt = tweenTarget.light;
if (lt != null)
{
mColor = lt.color;
}
else
{
tweenTarget = null;
mInitDone = false;
}
}
}
}
/// <summary>
/// Set the initial state.
/// </summary>
protected virtual void OnEnable ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (mInitDone) OnHover(UICamera.IsHighlighted(gameObject));
if (UICamera.currentTouch != null)
{
if (UICamera.currentTouch.pressed == gameObject) OnPress(true);
else if (UICamera.currentTouch.current == gameObject) OnHover(true);
}
}
/// <summary>
/// Reset the initial state.
/// </summary>
protected virtual void OnDisable ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (mInitDone && tweenTarget != null)
{
SetState(State.Normal, true);
TweenColor tc = tweenTarget.GetComponent<TweenColor>();
if (tc != null)
{
tc.value = mColor;
tc.enabled = false;
}
}
}
/// <summary>
/// Set the hover state.
/// </summary>
protected virtual void OnHover (bool isOver)
{
if (isEnabled)
{
if (!mInitDone) OnInit();
if (tweenTarget != null) SetState(isOver ? State.Hover : State.Normal, false);
}
}
/// <summary>
/// Set the pressed state.
/// </summary>
protected virtual void OnPress (bool isPressed)
{
if (isEnabled && UICamera.currentTouch != null)
{
if (!mInitDone) OnInit();
if (tweenTarget != null)
{
if (isPressed)
{
SetState(State.Pressed, false);
}
else if (UICamera.currentTouch.current == gameObject)
{
if (UICamera.currentScheme == UICamera.ControlScheme.Controller)
{
SetState(State.Hover, false);
}
else if (UICamera.currentScheme == UICamera.ControlScheme.Mouse && UICamera.hoveredObject == gameObject)
{
SetState(State.Hover, false);
}
else SetState(State.Normal, false);
}
else SetState(State.Normal, false);
}
}
}
/// <summary>
/// Set the pressed state on drag over.
/// </summary>
protected virtual void OnDragOver ()
{
if (isEnabled)
{
if (!mInitDone) OnInit();
if (tweenTarget != null) SetState(State.Pressed, false);
}
}
/// <summary>
/// Set the normal state on drag out.
/// </summary>
protected virtual void OnDragOut ()
{
if (isEnabled)
{
if (!mInitDone) OnInit();
if (tweenTarget != null) SetState(State.Normal, false);
}
}
/// <summary>
/// Set the selected state.
/// </summary>
protected virtual void OnSelect (bool isSelected)
{
if (isEnabled && (!isSelected || UICamera.currentScheme == UICamera.ControlScheme.Controller) && tweenTarget != null)
OnHover(isSelected);
}
/// <summary>
/// Change the visual state.
/// </summary>
public virtual void SetState (State state, bool instant)
{
if (!mInitDone)
{
mInitDone = true;
OnInit();
}
if (mState != state)
{
mState = state;
TweenColor tc;
switch (mState)
{
case State.Hover: tc = TweenColor.Begin(tweenTarget, duration, hover); break;
case State.Pressed: tc = TweenColor.Begin(tweenTarget, duration, pressed); break;
case State.Disabled: tc = TweenColor.Begin(tweenTarget, duration, disabledColor); break;
default: tc = TweenColor.Begin(tweenTarget, duration, mColor); break;
}
if (instant && tc != null)
{
tc.value = tc.to;
tc.enabled = false;
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIButtonColor.cs
|
C#
|
asf20
| 5,989
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Plays the specified sound.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Play Sound")]
public class UIPlaySound : MonoBehaviour
{
public enum Trigger
{
OnClick,
OnMouseOver,
OnMouseOut,
OnPress,
OnRelease,
Custom,
}
public AudioClip audioClip;
public Trigger trigger = Trigger.OnClick;
bool mIsOver = false;
#if UNITY_3_5
public float volume = 1f;
public float pitch = 1f;
#else
[Range(0f, 1f)] public float volume = 1f;
[Range(0f, 2f)] public float pitch = 1f;
#endif
void OnHover (bool isOver)
{
if (trigger == Trigger.OnMouseOver)
{
if (mIsOver == isOver) return;
mIsOver = isOver;
}
if (enabled && ((isOver && trigger == Trigger.OnMouseOver) || (!isOver && trigger == Trigger.OnMouseOut)))
NGUITools.PlaySound(audioClip, volume, pitch);
}
void OnPress (bool isPressed)
{
if (trigger == Trigger.OnPress)
{
if (mIsOver == isPressed) return;
mIsOver = isPressed;
}
if (enabled && ((isPressed && trigger == Trigger.OnPress) || (!isPressed && trigger == Trigger.OnRelease)))
NGUITools.PlaySound(audioClip, volume, pitch);
}
void OnClick ()
{
if (enabled && trigger == Trigger.OnClick)
NGUITools.PlaySound(audioClip, volume, pitch);
}
void OnSelect (bool isSelected)
{
if (enabled && (!isSelected || UICamera.currentScheme == UICamera.ControlScheme.Controller))
OnHover(isSelected);
}
public void Play ()
{
NGUITools.PlaySound(audioClip, volume, pitch);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIPlaySound.cs
|
C#
|
asf20
| 1,677
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Extended progress bar that has backwards compatibility logic and adds interaction support.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/NGUI Slider")]
public class UISlider : UIProgressBar
{
enum Direction
{
Horizontal,
Vertical,
Upgraded,
}
// Deprecated functionality. Use 'foregroundWidget' instead.
[HideInInspector][SerializeField] Transform foreground = null;
// Deprecated functionality
[HideInInspector][SerializeField] float rawValue = 1f; // Use 'value'
[HideInInspector][SerializeField] Direction direction = Direction.Upgraded; // Use 'fillDirection'
[HideInInspector][SerializeField] protected bool mInverted = false;
[System.Obsolete("Use 'value' instead")]
public float sliderValue { get { return this.value; } set { this.value = value; } }
[System.Obsolete("Use 'fillDirection' instead")]
public bool inverted { get { return isInverted; } set { } }
/// <summary>
/// Upgrade from legacy functionality.
/// </summary>
protected override void Upgrade ()
{
if (direction != Direction.Upgraded)
{
mValue = rawValue;
if (foreground != null)
mFG = foreground.GetComponent<UIWidget>();
if (direction == Direction.Horizontal)
{
mFill = mInverted ? FillDirection.RightToLeft : FillDirection.LeftToRight;
}
else
{
mFill = mInverted ? FillDirection.TopToBottom : FillDirection.BottomToTop;
}
direction = Direction.Upgraded;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
}
/// <summary>
/// Register an event listener.
/// </summary>
protected override void OnStart ()
{
GameObject bg = (mBG != null && mBG.collider != null) ? mBG.gameObject : gameObject;
UIEventListener bgl = UIEventListener.Get(bg);
bgl.onPress += OnPressBackground;
bgl.onDrag += OnDragBackground;
if (thumb != null && thumb.collider != null && (mFG == null || thumb != mFG.cachedTransform))
{
UIEventListener fgl = UIEventListener.Get(thumb.gameObject);
fgl.onPress += OnPressForeground;
fgl.onDrag += OnDragForeground;
}
}
/// <summary>
/// Position the scroll bar to be under the current touch.
/// </summary>
protected void OnPressBackground (GameObject go, bool isPressed)
{
if (UICamera.currentScheme == UICamera.ControlScheme.Controller) return;
mCam = UICamera.currentCamera;
value = ScreenToValue(UICamera.lastTouchPosition);
if (!isPressed && onDragFinished != null) onDragFinished();
}
/// <summary>
/// Position the scroll bar to be under the current touch.
/// </summary>
protected void OnDragBackground (GameObject go, Vector2 delta)
{
if (UICamera.currentScheme == UICamera.ControlScheme.Controller) return;
mCam = UICamera.currentCamera;
value = ScreenToValue(UICamera.lastTouchPosition);
}
/// <summary>
/// Save the position of the foreground on press.
/// </summary>
protected void OnPressForeground (GameObject go, bool isPressed)
{
if (UICamera.currentScheme == UICamera.ControlScheme.Controller) return;
if (isPressed)
{
mOffset = (mFG == null) ? 0f :
value - ScreenToValue(UICamera.lastTouchPosition);
}
else if (onDragFinished != null) onDragFinished();
}
/// <summary>
/// Drag the scroll bar in the specified direction.
/// </summary>
protected void OnDragForeground (GameObject go, Vector2 delta)
{
if (UICamera.currentScheme == UICamera.ControlScheme.Controller) return;
mCam = UICamera.currentCamera;
value = mOffset + ScreenToValue(UICamera.lastTouchPosition);
}
/// <summary>
/// Watch for key events and adjust the value accordingly.
/// </summary>
protected void OnKey (KeyCode key)
{
if (enabled)
{
float step = (numberOfSteps > 1f) ? 1f / (numberOfSteps - 1) : 0.125f;
if (fillDirection == FillDirection.LeftToRight || fillDirection == FillDirection.RightToLeft)
{
if (key == KeyCode.LeftArrow) value = mValue - step;
else if (key == KeyCode.RightArrow) value = mValue + step;
}
else
{
if (key == KeyCode.DownArrow) value = mValue - step;
else if (key == KeyCode.UpArrow) value = mValue + step;
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UISlider.cs
|
C#
|
asf20
| 4,337
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Sends a message to the remote object when something happens.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Button Message (Legacy)")]
public class UIButtonMessage : MonoBehaviour
{
public enum Trigger
{
OnClick,
OnMouseOver,
OnMouseOut,
OnPress,
OnRelease,
OnDoubleClick,
}
public GameObject target;
public string functionName;
public Trigger trigger = Trigger.OnClick;
public bool includeChildren = false;
bool mStarted = false;
void Start () { mStarted = true; }
void OnEnable () { if (mStarted) OnHover(UICamera.IsHighlighted(gameObject)); }
void OnHover (bool isOver)
{
if (enabled)
{
if (((isOver && trigger == Trigger.OnMouseOver) ||
(!isOver && trigger == Trigger.OnMouseOut))) Send();
}
}
void OnPress (bool isPressed)
{
if (enabled)
{
if (((isPressed && trigger == Trigger.OnPress) ||
(!isPressed && trigger == Trigger.OnRelease))) Send();
}
}
void OnSelect (bool isSelected)
{
if (enabled && (!isSelected || UICamera.currentScheme == UICamera.ControlScheme.Controller))
OnHover(isSelected);
}
void OnClick () { if (enabled && trigger == Trigger.OnClick) Send(); }
void OnDoubleClick () { if (enabled && trigger == Trigger.OnDoubleClick) Send(); }
void Send ()
{
if (string.IsNullOrEmpty(functionName)) return;
if (target == null) target = gameObject;
if (includeChildren)
{
Transform[] transforms = target.GetComponentsInChildren<Transform>();
for (int i = 0, imax = transforms.Length; i < imax; ++i)
{
Transform t = transforms[i];
t.gameObject.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver);
}
}
else
{
target.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIButtonMessage.cs
|
C#
|
asf20
| 1,983
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using AnimationOrTween;
using System.Collections.Generic;
/// <summary>
/// Simple toggle functionality.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/Toggle")]
public class UIToggle : UIWidgetContainer
{
/// <summary>
/// List of all the active toggles currently in the scene.
/// </summary>
static public BetterList<UIToggle> list = new BetterList<UIToggle>();
/// <summary>
/// Current toggle that sent a state change notification.
/// </summary>
static public UIToggle current;
/// <summary>
/// If set to anything other than '0', all active toggles in this group will behave as radio buttons.
/// </summary>
public int group = 0;
/// <summary>
/// Sprite that's visible when the 'isActive' status is 'true'.
/// </summary>
public UIWidget activeSprite;
/// <summary>
/// Animation to play on the active sprite, if any.
/// </summary>
public Animation activeAnimation;
/// <summary>
/// Whether the toggle starts checked.
/// </summary>
public bool startsActive = false;
/// <summary>
/// If checked, tween-based transition will be instant instead.
/// </summary>
public bool instantTween = false;
/// <summary>
/// Can the radio button option be 'none'?
/// </summary>
public bool optionCanBeNone = false;
/// <summary>
/// Callbacks triggered when the toggle's state changes.
/// </summary>
public List<EventDelegate> onChange = new List<EventDelegate>();
/// <summary>
/// Deprecated functionality. Use the 'group' option instead.
/// </summary>
[HideInInspector][SerializeField] UISprite checkSprite = null;
[HideInInspector][SerializeField] Animation checkAnimation;
[HideInInspector][SerializeField] GameObject eventReceiver;
[HideInInspector][SerializeField] string functionName = "OnActivate";
[HideInInspector][SerializeField] bool startsChecked = false; // Use 'startsActive' instead
bool mIsActive = true;
bool mStarted = false;
/// <summary>
/// Whether the toggle is checked.
/// </summary>
public bool value
{
get { return mIsActive; }
set { if (group == 0 || value || optionCanBeNone || !mStarted) Set(value); }
}
[System.Obsolete("Use 'value' instead")]
public bool isChecked { get { return value; } set { this.value = value; } }
/// <summary>
/// Return the first active toggle within the specified group.
/// </summary>
static public UIToggle GetActiveToggle (int group)
{
for (int i = 0; i < list.size; ++i)
{
UIToggle toggle = list[i];
if (toggle != null && toggle.group == group && toggle.mIsActive)
return toggle;
}
return null;
}
void OnEnable () { list.Add(this); }
void OnDisable () { list.Remove(this); }
/// <summary>
/// Activate the initial state.
/// </summary>
void Start ()
{
if (startsChecked)
{
startsChecked = false;
startsActive = true;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
// Auto-upgrade
if (!Application.isPlaying)
{
if (checkSprite != null && activeSprite == null)
{
activeSprite = checkSprite;
checkSprite = null;
}
if (checkAnimation != null && activeAnimation == null)
{
activeAnimation = checkAnimation;
checkAnimation = null;
}
if (Application.isPlaying && activeSprite != null)
activeSprite.alpha = startsActive ? 1f : 0f;
if (EventDelegate.IsValid(onChange))
{
eventReceiver = null;
functionName = null;
}
}
else
{
mIsActive = !startsActive;
mStarted = true;
bool instant = instantTween;
instantTween = true;
Set(startsActive);
instantTween = instant;
}
}
/// <summary>
/// Check or uncheck on click.
/// </summary>
void OnClick () { if (enabled) value = !value; }
/// <summary>
/// Fade out or fade in the active sprite and notify the OnChange event listener.
/// </summary>
void Set (bool state)
{
if (!mStarted)
{
mIsActive = state;
startsActive = state;
if (activeSprite != null) activeSprite.alpha = state ? 1f : 0f;
}
else if (mIsActive != state)
{
// Uncheck all other toggles
if (group != 0 && state)
{
for (int i = 0, imax = list.size; i < imax; )
{
UIToggle cb = list[i];
if (cb != this && cb.group == group) cb.Set(false);
if (list.size != imax)
{
imax = list.size;
i = 0;
}
else ++i;
}
}
// Remember the state
mIsActive = state;
// Tween the color of the active sprite
if (activeSprite != null)
{
if (instantTween)
{
activeSprite.alpha = mIsActive ? 1f : 0f;
}
else
{
TweenAlpha.Begin(activeSprite.gameObject, 0.15f, mIsActive ? 1f : 0f);
}
}
if (current == null)
{
current = this;
if (EventDelegate.IsValid(onChange))
{
EventDelegate.Execute(onChange);
}
else if (eventReceiver != null && !string.IsNullOrEmpty(functionName))
{
// Legacy functionality support (for backwards compatibility)
eventReceiver.SendMessage(functionName, mIsActive, SendMessageOptions.DontRequireReceiver);
}
current = null;
}
// Play the checkmark animation
if (activeAnimation != null)
{
ActiveAnimation aa = ActiveAnimation.Play(activeAnimation, state ? Direction.Forward : Direction.Reverse);
if (instantTween) aa.Finish();
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIToggle.cs
|
C#
|
asf20
| 5,487
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Deprecated component. Use UIKeyNavigation instead.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/Button Keys (Legacy)")]
public class UIButtonKeys : UIKeyNavigation
{
public UIButtonKeys selectOnClick;
public UIButtonKeys selectOnUp;
public UIButtonKeys selectOnDown;
public UIButtonKeys selectOnLeft;
public UIButtonKeys selectOnRight;
protected override void OnEnable ()
{
Upgrade();
base.OnEnable();
}
public void Upgrade ()
{
if (onClick == null && selectOnClick != null)
{
onClick = selectOnClick.gameObject;
selectOnClick = null;
NGUITools.SetDirty(this);
}
if (onLeft == null && selectOnLeft != null)
{
onLeft = selectOnLeft.gameObject;
selectOnLeft = null;
NGUITools.SetDirty(this);
}
if (onRight == null && selectOnRight != null)
{
onRight = selectOnRight.gameObject;
selectOnRight = null;
NGUITools.SetDirty(this);
}
if (onUp == null && selectOnUp != null)
{
onUp = selectOnUp.gameObject;
selectOnUp = null;
NGUITools.SetDirty(this);
}
if (onDown == null && selectOnDown != null)
{
onDown = selectOnDown.gameObject;
selectOnDown = null;
NGUITools.SetDirty(this);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIButtonKeys.cs
|
C#
|
asf20
| 1,423
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections;
/// <summary>
/// Allows dragging of the specified target object by mouse or touch, optionally limiting it to be within the UIPanel's clipped rectangle.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/Drag Object")]
public class UIDragObject : MonoBehaviour
{
public enum DragEffect
{
None,
Momentum,
MomentumAndSpring,
}
/// <summary>
/// Target object that will be dragged.
/// </summary>
public Transform target;
/// <summary>
/// Scale value applied to the drag delta. Set X or Y to 0 to disallow dragging in that direction.
/// </summary>
public Vector3 dragMovement { get { return scale; } set { scale = value; } }
/// <summary>
/// Momentum added from the mouse scroll wheel.
/// </summary>
public Vector3 scrollMomentum = Vector3.zero;
/// <summary>
/// Whether the dragging will be restricted to be within the parent panel's bounds.
/// </summary>
public bool restrictWithinPanel = false;
/// <summary>
/// Rectangle to be used as the draggable object's bounds. If none specified, all widgets' bounds get added up.
/// </summary>
public UIRect contentRect = null;
/// <summary>
/// Effect to apply when dragging.
/// </summary>
public DragEffect dragEffect = DragEffect.MomentumAndSpring;
/// <summary>
/// How much momentum gets applied when the press is released after dragging.
/// </summary>
public float momentumAmount = 35f;
// Obsolete property. Use 'dragMovement' instead.
[SerializeField] protected Vector3 scale = new Vector3(1f, 1f, 0f);
// Obsolete property. Use 'scrollMomentum' instead.
[SerializeField][HideInInspector] float scrollWheelFactor = 0f;
Plane mPlane;
Vector3 mTargetPos;
Vector3 mLastPos;
UIPanel mPanel;
Vector3 mMomentum = Vector3.zero;
Vector3 mScroll = Vector3.zero;
Bounds mBounds;
int mTouchID = 0;
bool mStarted = false;
bool mPressed = false;
/// <summary>
/// Auto-upgrade the legacy data.
/// </summary>
void OnEnable ()
{
if (scrollWheelFactor != 0f)
{
scrollMomentum = scale * scrollWheelFactor;
scrollWheelFactor = 0f;
}
if (contentRect == null && target != null && Application.isPlaying)
{
UIWidget w = target.GetComponent<UIWidget>();
if (w != null) contentRect = w;
}
}
void OnDisable () { mStarted = false; }
/// <summary>
/// Find the panel responsible for this object.
/// </summary>
void FindPanel ()
{
mPanel = (target != null) ? UIPanel.Find(target.transform.parent) : null;
if (mPanel == null) restrictWithinPanel = false;
}
/// <summary>
/// Recalculate the bounds of the dragged content.
/// </summary>
void UpdateBounds ()
{
if (contentRect)
{
Transform t = mPanel.cachedTransform;
Matrix4x4 toLocal = t.worldToLocalMatrix;
Vector3[] corners = contentRect.worldCorners;
for (int i = 0; i < 4; ++i) corners[i] = toLocal.MultiplyPoint3x4(corners[i]);
mBounds = new Bounds(corners[0], Vector3.zero);
for (int i = 1; i < 4; ++i) mBounds.Encapsulate(corners[i]);
}
else
{
mBounds = NGUIMath.CalculateRelativeWidgetBounds(mPanel.cachedTransform, target);
}
}
/// <summary>
/// Create a plane on which we will be performing the dragging.
/// </summary>
void OnPress (bool pressed)
{
if (enabled && NGUITools.GetActive(gameObject) && target != null)
{
if (pressed)
{
if (!mPressed)
{
// Remove all momentum on press
mTouchID = UICamera.currentTouchID;
mPressed = true;
mStarted = false;
CancelMovement();
if (restrictWithinPanel && mPanel == null) FindPanel();
if (restrictWithinPanel) UpdateBounds();
// Disable the spring movement
CancelSpring();
// Create the plane to drag along
Transform trans = UICamera.currentCamera.transform;
mPlane = new Plane((mPanel != null ? mPanel.cachedTransform.rotation : trans.rotation) * Vector3.back, UICamera.lastHit.point);
}
}
else if (mPressed && mTouchID == UICamera.currentTouchID)
{
mPressed = false;
if (restrictWithinPanel && dragEffect == DragEffect.MomentumAndSpring)
{
if (mPanel.ConstrainTargetToBounds(target, ref mBounds, false))
CancelMovement();
}
}
}
}
/// <summary>
/// Drag the object along the plane.
/// </summary>
void OnDrag (Vector2 delta)
{
if (mPressed && mTouchID == UICamera.currentTouchID && enabled && NGUITools.GetActive(gameObject) && target != null)
{
UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;
Ray ray = UICamera.currentCamera.ScreenPointToRay(UICamera.currentTouch.pos);
float dist = 0f;
if (mPlane.Raycast(ray, out dist))
{
Vector3 currentPos = ray.GetPoint(dist);
Vector3 offset = currentPos - mLastPos;
mLastPos = currentPos;
if (!mStarted)
{
mStarted = true;
offset = Vector3.zero;
}
if (offset.x != 0f || offset.y != 0f)
{
offset = target.InverseTransformDirection(offset);
offset.Scale(scale);
offset = target.TransformDirection(offset);
}
// Adjust the momentum
if (dragEffect != DragEffect.None)
mMomentum = Vector3.Lerp(mMomentum, mMomentum + offset * (0.01f * momentumAmount), 0.67f);
// Adjust the position and bounds
Vector3 before = target.localPosition;
Move(offset);
// We want to constrain the UI to be within bounds
if (restrictWithinPanel)
{
mBounds.center = mBounds.center + (target.localPosition - before);
// Constrain the UI to the bounds, and if done so, immediately eliminate the momentum
if (dragEffect != DragEffect.MomentumAndSpring && mPanel.ConstrainTargetToBounds(target, ref mBounds, true))
CancelMovement();
}
}
}
}
/// <summary>
/// Move the dragged object by the specified amount.
/// </summary>
void Move (Vector3 worldDelta)
{
if (mPanel != null)
{
mTargetPos += worldDelta;
target.position = mTargetPos;
Vector3 after = target.localPosition;
after.x = Mathf.Round(after.x);
after.y = Mathf.Round(after.y);
target.localPosition = after;
UIScrollView ds = mPanel.GetComponent<UIScrollView>();
if (ds != null) ds.UpdateScrollbars(true);
}
else target.position += worldDelta;
}
/// <summary>
/// Apply the dragging momentum.
/// </summary>
void LateUpdate ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (target == null) return;
float delta = RealTime.deltaTime;
mMomentum -= mScroll;
mScroll = NGUIMath.SpringLerp(mScroll, Vector3.zero, 20f, delta);
if (!mPressed)
{
// No momentum? Exit.
if (mMomentum.magnitude < 0.0001f) return;
// Apply the momentum
if (mPanel == null) FindPanel();
Move(NGUIMath.SpringDampen(ref mMomentum, 9f, delta));
if (restrictWithinPanel && mPanel != null)
{
UpdateBounds();
if (mPanel.ConstrainTargetToBounds(target, ref mBounds, dragEffect == DragEffect.None))
{
CancelMovement();
}
else CancelSpring();
}
}
else mTargetPos = (target != null) ? target.position : Vector3.zero;
// Dampen the momentum
NGUIMath.SpringDampen(ref mMomentum, 9f, delta);
}
/// <summary>
/// Cancel all movement.
/// </summary>
public void CancelMovement ()
{
mTargetPos = (target != null) ? target.position : Vector3.zero;
mMomentum = Vector3.zero;
mScroll = Vector3.zero;
}
/// <summary>
/// Cancel the spring movement.
/// </summary>
public void CancelSpring ()
{
SpringPosition sp = target.GetComponent<SpringPosition>();
if (sp != null) sp.enabled = false;
}
/// <summary>
/// If the object should support the scroll wheel, do it.
/// </summary>
void OnScroll (float delta)
{
if (enabled && NGUITools.GetActive(gameObject))
mScroll -= scrollMomentum * (delta * 0.05f);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIDragObject.cs
|
C#
|
asf20
| 7,986
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// When Drag & Drop event begins in UIDragDropItem, it will re-parent itself to the UIDragDropRoot instead.
/// It's useful when you're dragging something out of a clipped panel: you will want to reparent it before
/// it can be dragged outside.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Drag and Drop Root")]
public class UIDragDropRoot : MonoBehaviour
{
static public Transform root;
void OnEnable () { root = transform; }
void OnDisable () { if (root == transform) root = null; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIDragDropRoot.cs
|
C#
|
asf20
| 718
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// All children added to the game object with this script will be arranged into a table
/// with rows and columns automatically adjusting their size to fit their content
/// (think "table" tag in HTML).
/// </summary>
[AddComponentMenu("NGUI/Interaction/Table")]
public class UITable : UIWidgetContainer
{
public delegate void OnReposition ();
public enum Direction
{
Down,
Up,
}
public enum Sorting
{
None,
Alphabetic,
Horizontal,
Vertical,
Custom,
}
/// <summary>
/// How many columns there will be before a new line is started. 0 means unlimited.
/// </summary>
public int columns = 0;
/// <summary>
/// Which way the new lines will be added.
/// </summary>
public Direction direction = Direction.Down;
/// <summary>
/// How to sort the grid's elements.
/// </summary>
public Sorting sorting = Sorting.None;
/// <summary>
/// Whether inactive children will be discarded from the table's calculations.
/// </summary>
public bool hideInactive = true;
/// <summary>
/// Whether the parent container will be notified of the table's changes.
/// </summary>
public bool keepWithinPanel = false;
/// <summary>
/// Padding around each entry, in pixels.
/// </summary>
public Vector2 padding = Vector2.zero;
/// <summary>
/// Delegate function that will be called when the table repositions its content.
/// </summary>
public OnReposition onReposition;
protected UIPanel mPanel;
protected bool mInitDone = false;
protected bool mReposition = false;
protected List<Transform> mChildren = new List<Transform>();
// Use the 'sorting' property instead
[HideInInspector][SerializeField] bool sorted = false;
/// <summary>
/// Reposition the children on the next Update().
/// </summary>
public bool repositionNow { set { if (value) { mReposition = true; enabled = true; } } }
/// <summary>
/// Returns the list of table's children, sorted alphabetically if necessary.
/// </summary>
public List<Transform> children
{
get
{
if (mChildren.Count == 0)
{
Transform myTrans = transform;
mChildren.Clear();
for (int i = 0; i < myTrans.childCount; ++i)
{
Transform child = myTrans.GetChild(i);
if (child && child.gameObject && (!hideInactive || NGUITools.GetActive(child.gameObject)))
mChildren.Add(child);
}
if (sorting != Sorting.None || sorted)
{
if (sorting == Sorting.Alphabetic) mChildren.Sort(UIGrid.SortByName);
else if (sorting == Sorting.Horizontal) mChildren.Sort(UIGrid.SortHorizontal);
else if (sorting == Sorting.Vertical) mChildren.Sort(UIGrid.SortVertical);
else Sort(mChildren);
}
}
return mChildren;
}
}
/// <summary>
/// Want your own custom sorting logic? Override this function.
/// </summary>
protected virtual void Sort (List<Transform> list) { list.Sort(UIGrid.SortByName); }
/// <summary>
/// Positions the grid items, taking their own size into consideration.
/// </summary>
protected void RepositionVariableSize (List<Transform> children)
{
float xOffset = 0;
float yOffset = 0;
int cols = columns > 0 ? children.Count / columns + 1 : 1;
int rows = columns > 0 ? columns : children.Count;
Bounds[,] bounds = new Bounds[cols, rows];
Bounds[] boundsRows = new Bounds[rows];
Bounds[] boundsCols = new Bounds[cols];
int x = 0;
int y = 0;
for (int i = 0, imax = children.Count; i < imax; ++i)
{
Transform t = children[i];
Bounds b = NGUIMath.CalculateRelativeWidgetBounds(t, !hideInactive);
Vector3 scale = t.localScale;
b.min = Vector3.Scale(b.min, scale);
b.max = Vector3.Scale(b.max, scale);
bounds[y, x] = b;
boundsRows[x].Encapsulate(b);
boundsCols[y].Encapsulate(b);
if (++x >= columns && columns > 0)
{
x = 0;
++y;
}
}
x = 0;
y = 0;
for (int i = 0, imax = children.Count; i < imax; ++i)
{
Transform t = children[i];
Bounds b = bounds[y, x];
Bounds br = boundsRows[x];
Bounds bc = boundsCols[y];
Vector3 pos = t.localPosition;
pos.x = xOffset + b.extents.x - b.center.x;
pos.x += b.min.x - br.min.x + padding.x;
if (direction == Direction.Down)
{
pos.y = -yOffset - b.extents.y - b.center.y;
pos.y += (b.max.y - b.min.y - bc.max.y + bc.min.y) * 0.5f - padding.y;
}
else
{
pos.y = yOffset + (b.extents.y - b.center.y);
pos.y -= (b.max.y - b.min.y - bc.max.y + bc.min.y) * 0.5f - padding.y;
}
xOffset += br.max.x - br.min.x + padding.x * 2f;
t.localPosition = pos;
if (++x >= columns && columns > 0)
{
x = 0;
++y;
xOffset = 0f;
yOffset += bc.size.y + padding.y * 2f;
}
}
}
/// <summary>
/// Recalculate the position of all elements within the table, sorting them alphabetically if necessary.
/// </summary>
[ContextMenu("Execute")]
public virtual void Reposition ()
{
if (Application.isPlaying && !mInitDone && NGUITools.GetActive(this))
{
mReposition = true;
return;
}
if (!mInitDone) Init();
mReposition = false;
Transform myTrans = transform;
mChildren.Clear();
List<Transform> ch = children;
if (ch.Count > 0) RepositionVariableSize(ch);
if (keepWithinPanel && mPanel != null)
{
mPanel.ConstrainTargetToBounds(myTrans, true);
UIScrollView sv = mPanel.GetComponent<UIScrollView>();
if (sv != null) sv.UpdateScrollbars(true);
}
if (onReposition != null)
onReposition();
}
/// <summary>
/// Position the grid's contents when the script starts.
/// </summary>
protected virtual void Start ()
{
Init();
Reposition();
enabled = false;
}
/// <summary>
/// Find the necessary components.
/// </summary>
protected virtual void Init ()
{
mInitDone = true;
mPanel = NGUITools.FindInParents<UIPanel>(gameObject);
}
/// <summary>
/// Is it time to reposition? Do so now.
/// </summary>
protected virtual void LateUpdate ()
{
if (mReposition) Reposition();
enabled = false;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UITable.cs
|
C#
|
asf20
| 6,194
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Simple example script of how a button can be offset visibly when the mouse hovers over it or it gets pressed.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Button Offset")]
public class UIButtonOffset : MonoBehaviour
{
public Transform tweenTarget;
public Vector3 hover = Vector3.zero;
public Vector3 pressed = new Vector3(2f, -2f);
public float duration = 0.2f;
Vector3 mPos;
bool mStarted = false;
void Start ()
{
if (!mStarted)
{
mStarted = true;
if (tweenTarget == null) tweenTarget = transform;
mPos = tweenTarget.localPosition;
}
}
void OnEnable () { if (mStarted) OnHover(UICamera.IsHighlighted(gameObject)); }
void OnDisable ()
{
if (mStarted && tweenTarget != null)
{
TweenPosition tc = tweenTarget.GetComponent<TweenPosition>();
if (tc != null)
{
tc.value = mPos;
tc.enabled = false;
}
}
}
void OnPress (bool isPressed)
{
if (enabled)
{
if (!mStarted) Start();
TweenPosition.Begin(tweenTarget.gameObject, duration, isPressed ? mPos + pressed :
(UICamera.IsHighlighted(gameObject) ? mPos + hover : mPos)).method = UITweener.Method.EaseInOut;
}
}
void OnHover (bool isOver)
{
if (enabled)
{
if (!mStarted) Start();
TweenPosition.Begin(tweenTarget.gameObject, duration, isOver ? mPos + hover : mPos).method = UITweener.Method.EaseInOut;
}
}
void OnSelect (bool isSelected)
{
if (enabled && (!isSelected || UICamera.currentScheme == UICamera.ControlScheme.Controller))
OnHover(isSelected);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIButtonOffset.cs
|
C#
|
asf20
| 1,732
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Very simple script that can be attached to a slider and will control the volume of all sounds played via NGUITools.PlaySound,
/// which includes all of UI's sounds.
/// </summary>
[RequireComponent(typeof(UISlider))]
[AddComponentMenu("NGUI/Interaction/Sound Volume")]
public class UISoundVolume : MonoBehaviour
{
UISlider mSlider;
void Awake ()
{
mSlider = GetComponent<UISlider>();
mSlider.value = NGUITools.soundVolume;
EventDelegate.Add(mSlider.onChange, OnChange);
}
void OnChange ()
{
NGUITools.soundVolume = UISlider.current.value;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UISoundVolume.cs
|
C#
|
asf20
| 783
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Works together with UIDragCamera script, allowing you to drag a secondary camera while keeping it constrained to a certain area.
/// </summary>
[RequireComponent(typeof(Camera))]
[AddComponentMenu("NGUI/Interaction/Draggable Camera")]
public class UIDraggableCamera : MonoBehaviour
{
/// <summary>
/// Root object that will be used for drag-limiting bounds.
/// </summary>
public Transform rootForBounds;
/// <summary>
/// Scale value applied to the drag delta. Set X or Y to 0 to disallow dragging in that direction.
/// </summary>
public Vector2 scale = Vector2.one;
/// <summary>
/// Effect the scroll wheel will have on the momentum.
/// </summary>
public float scrollWheelFactor = 0f;
/// <summary>
/// Effect to apply when dragging.
/// </summary>
public UIDragObject.DragEffect dragEffect = UIDragObject.DragEffect.MomentumAndSpring;
/// <summary>
/// Whether the drag operation will be started smoothly, or if if it will be precise (but will have a noticeable "jump").
/// </summary>
public bool smoothDragStart = true;
/// <summary>
/// How much momentum gets applied when the press is released after dragging.
/// </summary>
public float momentumAmount = 35f;
Camera mCam;
Transform mTrans;
bool mPressed = false;
Vector2 mMomentum = Vector2.zero;
Bounds mBounds;
float mScroll = 0f;
UIRoot mRoot;
bool mDragStarted = false;
/// <summary>
/// Current momentum, exposed just in case it's needed.
/// </summary>
public Vector2 currentMomentum { get { return mMomentum; } set { mMomentum = value; } }
/// <summary>
/// Cache the common components.
/// </summary>
void Awake ()
{
mCam = camera;
mTrans = transform;
if (rootForBounds == null)
{
Debug.LogError(NGUITools.GetHierarchy(gameObject) + " needs the 'Root For Bounds' parameter to be set", this);
enabled = false;
}
}
/// <summary>
/// Cache the root.
/// </summary>
void Start () { mRoot = NGUITools.FindInParents<UIRoot>(gameObject); }
/// <summary>
/// Calculate the offset needed to be constrained within the panel's bounds.
/// </summary>
Vector3 CalculateConstrainOffset ()
{
if (rootForBounds == null || rootForBounds.childCount == 0) return Vector3.zero;
Vector3 bottomLeft = new Vector3(mCam.rect.xMin * Screen.width, mCam.rect.yMin * Screen.height, 0f);
Vector3 topRight = new Vector3(mCam.rect.xMax * Screen.width, mCam.rect.yMax * Screen.height, 0f);
bottomLeft = mCam.ScreenToWorldPoint(bottomLeft);
topRight = mCam.ScreenToWorldPoint(topRight);
Vector2 minRect = new Vector2(mBounds.min.x, mBounds.min.y);
Vector2 maxRect = new Vector2(mBounds.max.x, mBounds.max.y);
return NGUIMath.ConstrainRect(minRect, maxRect, bottomLeft, topRight);
}
/// <summary>
/// Constrain the current camera's position to be within the viewable area's bounds.
/// </summary>
public bool ConstrainToBounds (bool immediate)
{
if (mTrans != null && rootForBounds != null)
{
Vector3 offset = CalculateConstrainOffset();
if (offset.sqrMagnitude > 0f)
{
if (immediate)
{
mTrans.position -= offset;
}
else
{
SpringPosition sp = SpringPosition.Begin(gameObject, mTrans.position - offset, 13f);
sp.ignoreTimeScale = true;
sp.worldSpace = true;
}
return true;
}
}
return false;
}
/// <summary>
/// Calculate the bounds of all widgets under this game object.
/// </summary>
public void Press (bool isPressed)
{
if (isPressed) mDragStarted = false;
if (rootForBounds != null)
{
mPressed = isPressed;
if (isPressed)
{
// Update the bounds
mBounds = NGUIMath.CalculateAbsoluteWidgetBounds(rootForBounds);
// Remove all momentum on press
mMomentum = Vector2.zero;
mScroll = 0f;
// Disable the spring movement
SpringPosition sp = GetComponent<SpringPosition>();
if (sp != null) sp.enabled = false;
}
else if (dragEffect == UIDragObject.DragEffect.MomentumAndSpring)
{
ConstrainToBounds(false);
}
}
}
/// <summary>
/// Drag event receiver.
/// </summary>
public void Drag (Vector2 delta)
{
// Prevents the initial jump when the drag threshold gets passed
if (smoothDragStart && !mDragStarted)
{
mDragStarted = true;
return;
}
UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;
if (mRoot != null) delta *= mRoot.pixelSizeAdjustment;
Vector2 offset = Vector2.Scale(delta, -scale);
mTrans.localPosition += (Vector3)offset;
// Adjust the momentum
mMomentum = Vector2.Lerp(mMomentum, mMomentum + offset * (0.01f * momentumAmount), 0.67f);
// Constrain the UI to the bounds, and if done so, eliminate the momentum
if (dragEffect != UIDragObject.DragEffect.MomentumAndSpring && ConstrainToBounds(true))
{
mMomentum = Vector2.zero;
mScroll = 0f;
}
}
/// <summary>
/// If the object should support the scroll wheel, do it.
/// </summary>
public void Scroll (float delta)
{
if (enabled && NGUITools.GetActive(gameObject))
{
if (Mathf.Sign(mScroll) != Mathf.Sign(delta)) mScroll = 0f;
mScroll += delta * scrollWheelFactor;
}
}
/// <summary>
/// Apply the dragging momentum.
/// </summary>
void Update ()
{
float delta = RealTime.deltaTime;
if (mPressed)
{
// Disable the spring movement
SpringPosition sp = GetComponent<SpringPosition>();
if (sp != null) sp.enabled = false;
mScroll = 0f;
}
else
{
mMomentum += scale * (mScroll * 20f);
mScroll = NGUIMath.SpringLerp(mScroll, 0f, 20f, delta);
if (mMomentum.magnitude > 0.01f)
{
// Apply the momentum
mTrans.localPosition += (Vector3)NGUIMath.SpringDampen(ref mMomentum, 9f, delta);
mBounds = NGUIMath.CalculateAbsoluteWidgetBounds(rootForBounds);
if (!ConstrainToBounds(dragEffect == UIDragObject.DragEffect.None))
{
SpringPosition sp = GetComponent<SpringPosition>();
if (sp != null) sp.enabled = false;
}
return;
}
else mScroll = 0f;
}
// Dampen the momentum
NGUIMath.SpringDampen(ref mMomentum, 9f, delta);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIDraggableCamera.cs
|
C#
|
asf20
| 6,282
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Example script showing how to activate or deactivate MonoBehaviours with a toggle.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(UIToggle))]
[AddComponentMenu("NGUI/Interaction/Toggled Components")]
public class UIToggledComponents : MonoBehaviour
{
public List<MonoBehaviour> activate;
public List<MonoBehaviour> deactivate;
// Deprecated functionality
[HideInInspector][SerializeField] MonoBehaviour target;
[HideInInspector][SerializeField] bool inverse = false;
void Awake ()
{
// Legacy functionality -- auto-upgrade
if (target != null)
{
if (activate.Count == 0 && deactivate.Count == 0)
{
if (inverse) deactivate.Add(target);
else activate.Add(target);
}
else target = null;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
UIToggle toggle = GetComponent<UIToggle>();
EventDelegate.Add(toggle.onChange, Toggle);
}
public void Toggle ()
{
if (enabled)
{
for (int i = 0; i < activate.Count; ++i)
{
MonoBehaviour comp = activate[i];
comp.enabled = UIToggle.current.value;
}
for (int i = 0; i < deactivate.Count; ++i)
{
MonoBehaviour comp = deactivate[i];
comp.enabled = !UIToggle.current.value;
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIToggledComponents.cs
|
C#
|
asf20
| 1,538
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Attaching this script to a widget makes it react to key events such as tab, up, down, etc.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Key Navigation")]
public class UIKeyNavigation : MonoBehaviour
{
/// <summary>
/// List of all the active UINavigation components.
/// </summary>
static public BetterList<UIKeyNavigation> list = new BetterList<UIKeyNavigation>();
public enum Constraint
{
None,
Vertical,
Horizontal,
Explicit,
}
/// <summary>
/// If a selection target is not set, the target can be determined automatically, restricted by this constraint.
/// 'None' means free movement on both horizontal and vertical axis. 'Explicit' means the automatic logic will
/// not execute, and only the explicitly set values will be used.
/// </summary>
public Constraint constraint = Constraint.None;
/// <summary>
/// Which object will be selected when the Up button is pressed.
/// </summary>
public GameObject onUp;
/// <summary>
/// Which object will be selected when the Down button is pressed.
/// </summary>
public GameObject onDown;
/// <summary>
/// Which object will be selected when the Left button is pressed.
/// </summary>
public GameObject onLeft;
/// <summary>
/// Which object will be selected when the Right button is pressed.
/// </summary>
public GameObject onRight;
/// <summary>
/// Which object will get selected on click.
/// </summary>
public GameObject onClick;
/// <summary>
/// Whether the object this script is attached to will get selected as soon as this script is enabled.
/// </summary>
public bool startsSelected = false;
protected virtual void OnEnable ()
{
list.Add(this);
if (startsSelected)
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (UICamera.selectedObject == null || !NGUITools.GetActive(UICamera.selectedObject))
{
UICamera.currentScheme = UICamera.ControlScheme.Controller;
UICamera.selectedObject = gameObject;
}
}
}
protected virtual void OnDisable () { list.Remove(this); }
protected GameObject GetLeft ()
{
if (NGUITools.GetActive(onLeft)) return onLeft;
if (constraint == Constraint.Vertical || constraint == Constraint.Explicit) return null;
return Get(Vector3.left, true);
}
GameObject GetRight ()
{
if (NGUITools.GetActive(onRight)) return onRight;
if (constraint == Constraint.Vertical || constraint == Constraint.Explicit) return null;
return Get(Vector3.right, true);
}
protected GameObject GetUp ()
{
if (NGUITools.GetActive(onUp)) return onUp;
if (constraint == Constraint.Horizontal || constraint == Constraint.Explicit) return null;
return Get(Vector3.up, false);
}
protected GameObject GetDown ()
{
if (NGUITools.GetActive(onDown)) return onDown;
if (constraint == Constraint.Horizontal || constraint == Constraint.Explicit) return null;
return Get(Vector3.down, false);
}
protected GameObject Get (Vector3 myDir, bool horizontal)
{
Transform t = transform;
myDir = t.TransformDirection(myDir);
Vector3 myCenter = GetCenter(gameObject);
float min = float.MaxValue;
GameObject go = null;
for (int i = 0; i < list.size; ++i)
{
UIKeyNavigation nav = list[i];
if (nav == this) continue;
// Reject objects that are not within a 45 degree angle of the desired direction
Vector3 dir = GetCenter(nav.gameObject) - myCenter;
float dot = Vector3.Dot(myDir, dir.normalized);
if (dot < 0.707f) continue;
// Exaggerate the movement in the undesired direction
dir = t.InverseTransformDirection(dir);
if (horizontal) dir.y *= 2f;
else dir.x *= 2f;
// Compare the distance
float mag = dir.sqrMagnitude;
if (mag > min) continue;
go = nav.gameObject;
min = mag;
}
return go;
}
static protected Vector3 GetCenter (GameObject go)
{
UIWidget w = go.GetComponent<UIWidget>();
if (w != null)
{
Vector3[] corners = w.worldCorners;
return (corners[0] + corners[2]) * 0.5f;
}
return go.transform.position;
}
protected virtual void OnKey (KeyCode key)
{
if (!NGUITools.GetActive(this)) return;
GameObject go = null;
switch (key)
{
case KeyCode.LeftArrow:
go = GetLeft();
break;
case KeyCode.RightArrow:
go = GetRight();
break;
case KeyCode.UpArrow:
go = GetUp();
break;
case KeyCode.DownArrow:
go = GetDown();
break;
case KeyCode.Tab:
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
go = GetLeft();
if (go == null) go = GetUp();
if (go == null) go = GetDown();
if (go == null) go = GetRight();
}
else
{
go = GetRight();
if (go == null) go = GetDown();
if (go == null) go = GetUp();
if (go == null) go = GetLeft();
}
break;
}
if (go != null) UICamera.selectedObject = go;
}
protected virtual void OnClick ()
{
if (NGUITools.GetActive(this) && NGUITools.GetActive(onClick))
UICamera.selectedObject = onClick;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIKeyNavigation.cs
|
C#
|
asf20
| 5,161
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
[AddComponentMenu("NGUI/Interaction/Drag and Drop Container")]
public class UIDragDropContainer : MonoBehaviour
{
public Transform reparentTarget;
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIDragDropContainer.cs
|
C#
|
asf20
| 357
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This script makes it possible for a scroll view to wrap its content, creating endless scroll views.
/// Usage: simply attach this script underneath your scroll view where you would normally place a UIGrid:
///
/// + Scroll View
/// |- UIWrappedContent
/// |-- Item 1
/// |-- Item 2
/// |-- Item 3
/// </summary>
[AddComponentMenu("NGUI/Interaction/Wrap Content")]
public class UIWrapContent : MonoBehaviour
{
/// <summary>
/// Width or height of the child items for positioning purposes.
/// </summary>
public int itemSize = 100;
/// <summary>
/// Whether the content will be automatically culled. Enabling this will improve performance in scroll views that contain a lot of items.
/// </summary>
public bool cullContent = true;
Transform mTrans;
UIPanel mPanel;
UIScrollView mScroll;
bool mHorizontal = false;
BetterList<Transform> mChildren = new BetterList<Transform>();
/// <summary>
/// Initialize everything and register a callback with the UIPanel to be notified when the clipping region moves.
/// </summary>
protected virtual void Start ()
{
SortBasedOnScrollMovement();
WrapContent();
if (mScroll != null)
{
mScroll.GetComponent<UIPanel>().onClipMove = OnMove;
mScroll.restrictWithinPanel = false;
if (mScroll.dragEffect == UIScrollView.DragEffect.MomentumAndSpring)
mScroll.dragEffect = UIScrollView.DragEffect.Momentum;
}
}
/// <summary>
/// Callback triggered by the UIPanel when its clipping region moves (for example when it's being scrolled).
/// </summary>
protected virtual void OnMove (UIPanel panel) { WrapContent(); }
/// <summary>
/// Immediately reposition all children.
/// </summary>
[ContextMenu("Sort Based on Scroll Movement")]
public void SortBasedOnScrollMovement ()
{
if (!CacheScrollView()) return;
// Cache all children and place them in order
mChildren.Clear();
for (int i = 0; i < mTrans.childCount; ++i)
mChildren.Add(mTrans.GetChild(i));
// Sort the list of children so that they are in order
if (mHorizontal) mChildren.Sort(UIGrid.SortHorizontal);
else mChildren.Sort(UIGrid.SortVertical);
ResetChildPositions();
}
/// <summary>
/// Immediately reposition all children, sorting them alphabetically.
/// </summary>
[ContextMenu("Sort Alphabetically")]
public void SortAlphabetically ()
{
if (!CacheScrollView()) return;
// Cache all children and place them in order
mChildren.Clear();
for (int i = 0; i < mTrans.childCount; ++i)
mChildren.Add(mTrans.GetChild(i));
// Sort the list of children so that they are in order
mChildren.Sort(UIGrid.SortByName);
ResetChildPositions();
}
/// <summary>
/// Cache the scroll view and return 'false' if the scroll view is not found.
/// </summary>
protected bool CacheScrollView ()
{
mTrans = transform;
mPanel = NGUITools.FindInParents<UIPanel>(gameObject);
mScroll = mPanel.GetComponent<UIScrollView>();
if (mScroll == null) return false;
if (mScroll.movement == UIScrollView.Movement.Horizontal) mHorizontal = true;
else if (mScroll.movement == UIScrollView.Movement.Vertical) mHorizontal = false;
else return false;
return true;
}
/// <summary>
/// Helper function that resets the position of all the children.
/// </summary>
void ResetChildPositions ()
{
for (int i = 0; i < mChildren.size; ++i)
{
Transform t = mChildren[i];
t.localPosition = mHorizontal ? new Vector3(i * itemSize, 0f, 0f) : new Vector3(0f, -i * itemSize, 0f);
}
}
/// <summary>
/// Wrap all content, repositioning all children as needed.
/// </summary>
public void WrapContent ()
{
float extents = itemSize * mChildren.size * 0.5f;
Vector3[] corners = mPanel.worldCorners;
for (int i = 0; i < 4; ++i)
{
Vector3 v = corners[i];
v = mTrans.InverseTransformPoint(v);
corners[i] = v;
}
Vector3 center = Vector3.Lerp(corners[0], corners[2], 0.5f);
if (mHorizontal)
{
float min = corners[0].x - itemSize;
float max = corners[2].x + itemSize;
for (int i = 0; i < mChildren.size; ++i)
{
Transform t = mChildren[i];
float distance = t.localPosition.x - center.x;
if (distance < -extents)
{
t.localPosition += new Vector3(extents * 2f, 0f, 0f);
distance = t.localPosition.x - center.x;
UpdateItem(t, i);
}
else if (distance > extents)
{
t.localPosition -= new Vector3(extents * 2f, 0f, 0f);
distance = t.localPosition.x - center.x;
UpdateItem(t, i);
}
if (cullContent)
{
distance += mPanel.clipOffset.x - mTrans.localPosition.x;
if (!UICamera.IsPressed(t.gameObject))
NGUITools.SetActive(t.gameObject, (distance > min && distance < max), false);
}
}
}
else
{
float min = corners[0].y - itemSize;
float max = corners[2].y + itemSize;
for (int i = 0; i < mChildren.size; ++i)
{
Transform t = mChildren[i];
float distance = t.localPosition.y - center.y;
if (distance < -extents)
{
t.localPosition += new Vector3(0f, extents * 2f, 0f);
distance = t.localPosition.y - center.y;
UpdateItem(t, i);
}
else if (distance > extents)
{
t.localPosition -= new Vector3(0f, extents * 2f, 0f);
distance = t.localPosition.y - center.y;
UpdateItem(t, i);
}
if (cullContent)
{
distance += mPanel.clipOffset.y - mTrans.localPosition.y;
if (!UICamera.IsPressed(t.gameObject))
NGUITools.SetActive(t.gameObject, (distance > min && distance < max), false);
}
}
}
}
/// <summary>
/// Want to update the content of items as they are scrolled? Override this function.
/// </summary>
protected virtual void UpdateItem (Transform item, int index) {}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIWrapContent.cs
|
C#
|
asf20
| 5,911
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This script can be used to forward events from one object to another.
/// In most cases you should use UIEventListener script instead. For example:
/// UIEventListener.Get(gameObject).onClick += MyClickFunction;
/// </summary>
[AddComponentMenu("NGUI/Interaction/Forward Events (Legacy)")]
public class UIForwardEvents : MonoBehaviour
{
public GameObject target;
public bool onHover = false;
public bool onPress = false;
public bool onClick = false;
public bool onDoubleClick = false;
public bool onSelect = false;
public bool onDrag = false;
public bool onDrop = false;
public bool onSubmit = false;
public bool onScroll = false;
void OnHover (bool isOver)
{
if (onHover && target != null)
{
target.SendMessage("OnHover", isOver, SendMessageOptions.DontRequireReceiver);
}
}
void OnPress (bool pressed)
{
if (onPress && target != null)
{
target.SendMessage("OnPress", pressed, SendMessageOptions.DontRequireReceiver);
}
}
void OnClick ()
{
if (onClick && target != null)
{
target.SendMessage("OnClick", SendMessageOptions.DontRequireReceiver);
}
}
void OnDoubleClick ()
{
if (onDoubleClick && target != null)
{
target.SendMessage("OnDoubleClick", SendMessageOptions.DontRequireReceiver);
}
}
void OnSelect (bool selected)
{
if (onSelect && target != null)
{
target.SendMessage("OnSelect", selected, SendMessageOptions.DontRequireReceiver);
}
}
void OnDrag (Vector2 delta)
{
if (onDrag && target != null)
{
target.SendMessage("OnDrag", delta, SendMessageOptions.DontRequireReceiver);
}
}
void OnDrop (GameObject go)
{
if (onDrop && target != null)
{
target.SendMessage("OnDrop", go, SendMessageOptions.DontRequireReceiver);
}
}
void OnSubmit ()
{
if (onSubmit && target != null)
{
target.SendMessage("OnSubmit", SendMessageOptions.DontRequireReceiver);
}
}
void OnScroll (float delta)
{
if (onScroll && target != null)
{
target.SendMessage("OnScroll", delta, SendMessageOptions.DontRequireReceiver);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIForwardEvents.cs
|
C#
|
asf20
| 2,270
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Simple progress bar that fills itself based on the specified value.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/NGUI Progress Bar")]
public class UIProgressBar : UIWidgetContainer
{
public enum FillDirection
{
LeftToRight,
RightToLeft,
BottomToTop,
TopToBottom,
}
/// <summary>
/// Current slider. This value is set prior to the callback function being triggered.
/// </summary>
static public UIProgressBar current;
/// <summary>
/// Delegate triggered when the scroll bar stops being dragged.
/// Useful for things like centering on the closest valid object, for example.
/// </summary>
public OnDragFinished onDragFinished;
public delegate void OnDragFinished ();
/// <summary>
/// Object that acts as a thumb.
/// </summary>
public Transform thumb;
[HideInInspector][SerializeField] protected UIWidget mBG;
[HideInInspector][SerializeField] protected UIWidget mFG;
[HideInInspector][SerializeField] protected float mValue = 1f;
[HideInInspector][SerializeField] protected FillDirection mFill = FillDirection.LeftToRight;
protected Transform mTrans;
protected bool mIsDirty = false;
protected Camera mCam;
protected float mOffset = 0f;
/// <summary>
/// Number of steps the slider should be divided into. For example 5 means possible values of 0, 0.25, 0.5, 0.75, and 1.0.
/// </summary>
public int numberOfSteps = 0;
/// <summary>
/// Callbacks triggered when the scroll bar's value changes.
/// </summary>
public List<EventDelegate> onChange = new List<EventDelegate>();
/// <summary>
/// Cached for speed.
/// </summary>
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
/// <summary>
/// Camera used to draw the scroll bar.
/// </summary>
public Camera cachedCamera { get { if (mCam == null) mCam = NGUITools.FindCameraForLayer(gameObject.layer); return mCam; } }
/// <summary>
/// Widget used for the foreground.
/// </summary>
public UIWidget foregroundWidget { get { return mFG; } set { if (mFG != value) { mFG = value; mIsDirty = true; } } }
/// <summary>
/// Widget used for the background.
/// </summary>
public UIWidget backgroundWidget { get { return mBG; } set { if (mBG != value) { mBG = value; mIsDirty = true; } } }
/// <summary>
/// The scroll bar's direction.
/// </summary>
public FillDirection fillDirection
{
get
{
return mFill;
}
set
{
if (mFill != value)
{
mFill = value;
ForceUpdate();
}
}
}
/// <summary>
/// Modifiable value for the scroll bar, 0-1 range.
/// </summary>
public float value
{
get
{
if (numberOfSteps > 1) return Mathf.Round(mValue * (numberOfSteps - 1)) / (numberOfSteps - 1);
return mValue;
}
set
{
float val = Mathf.Clamp01(value);
if (mValue != val)
{
float before = this.value;
mValue = val;
if (before != this.value)
{
ForceUpdate();
if (current == null && NGUITools.GetActive(this) && EventDelegate.IsValid(onChange))
{
current = this;
EventDelegate.Execute(onChange);
current = null;
}
}
#if UNITY_EDITOR
if (!Application.isPlaying)
NGUITools.SetDirty(this);
#endif
}
}
}
/// <summary>
/// Allows to easily change the scroll bar's alpha, affecting both the foreground and the background sprite at once.
/// </summary>
public float alpha
{
get
{
if (mFG != null) return mFG.alpha;
if (mBG != null) return mBG.alpha;
return 1f;
}
set
{
if (mFG != null)
{
mFG.alpha = value;
if (mFG.collider != null) mFG.collider.enabled = mFG.alpha > 0.001f;
}
if (mBG != null)
{
mBG.alpha = value;
if (mBG.collider != null) mBG.collider.enabled = mBG.alpha > 0.001f;
}
if (thumb != null)
{
UIWidget w = thumb.GetComponent<UIWidget>();
if (w != null)
{
w.alpha = value;
if (w.collider != null) w.collider.enabled = w.alpha > 0.001f;
}
}
}
}
/// <summary>
/// Whether the progress bar is horizontal in nature. Convenience function.
/// </summary>
protected bool isHorizontal { get { return (mFill == FillDirection.LeftToRight || mFill == FillDirection.RightToLeft); } }
/// <summary>
/// Whether the progress bar is inverted in its behaviour. Convenience function.
/// </summary>
protected bool isInverted { get { return (mFill == FillDirection.RightToLeft || mFill == FillDirection.TopToBottom); } }
/// <summary>
/// Register the event listeners.
/// </summary>
protected void Start ()
{
Upgrade();
if (Application.isPlaying)
{
if (mFG == null)
{
Debug.LogWarning("Progress bar needs a foreground widget to work with", this);
enabled = false;
return;
}
if (mBG != null) mBG.autoResizeBoxCollider = true;
OnStart();
if (current == null && onChange != null)
{
current = this;
EventDelegate.Execute(onChange);
current = null;
}
}
ForceUpdate();
}
/// <summary>
/// Used to upgrade from legacy functionality.
/// </summary>
protected virtual void Upgrade () { }
/// <summary>
/// Functionality for derived classes.
/// </summary>
protected virtual void OnStart() { }
/// <summary>
/// Update the value of the scroll bar if necessary.
/// </summary>
protected void Update ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (mIsDirty) ForceUpdate();
}
/// <summary>
/// Invalidate the scroll bar.
/// </summary>
protected void OnValidate ()
{
// For some bizarre reason Unity calls this function on prefabs, even if prefabs
// are not actually used in the scene, nor selected in inspector. Dafuq?
if (NGUITools.GetActive(this))
{
Upgrade();
mIsDirty = true;
float val = Mathf.Clamp01(mValue);
if (mValue != val) mValue = val;
if (numberOfSteps < 0) numberOfSteps = 0;
else if (numberOfSteps > 20) numberOfSteps = 20;
ForceUpdate();
}
else
{
float val = Mathf.Clamp01(mValue);
if (mValue != val) mValue = val;
if (numberOfSteps < 0) numberOfSteps = 0;
else if (numberOfSteps > 20) numberOfSteps = 20;
}
}
/// <summary>
/// Drag the scroll bar by the specified on-screen amount.
/// </summary>
protected float ScreenToValue (Vector2 screenPos)
{
// Create a plane
Transform trans = cachedTransform;
Plane plane = new Plane(trans.rotation * Vector3.back, trans.position);
// If the ray doesn't hit the plane, do nothing
float dist;
Ray ray = cachedCamera.ScreenPointToRay(screenPos);
if (!plane.Raycast(ray, out dist)) return value;
// Transform the point from world space to local space
return LocalToValue(trans.InverseTransformPoint(ray.GetPoint(dist)));
}
/// <summary>
/// Calculate the value of the progress bar given the specified local position.
/// </summary>
protected virtual float LocalToValue (Vector2 localPos)
{
if (mFG != null)
{
Vector3[] corners = mFG.localCorners;
Vector3 size = (corners[2] - corners[0]);
if (isHorizontal)
{
float diff = (localPos.x - corners[0].x) / size.x;
return isInverted ? 1f - diff : diff;
}
else
{
float diff = (localPos.y - corners[0].y) / size.y;
return isInverted ? 1f - diff : diff;
}
}
return value;
}
/// <summary>
/// Update the value of the scroll bar.
/// </summary>
public virtual void ForceUpdate ()
{
mIsDirty = false;
if (mFG != null)
{
UISprite sprite = mFG as UISprite;
if (isHorizontal)
{
if (sprite != null && sprite.type == UISprite.Type.Filled)
{
sprite.fillDirection = UISprite.FillDirection.Horizontal;
sprite.invert = isInverted;
sprite.fillAmount = value;
}
else
{
mFG.drawRegion = isInverted ?
new Vector4(1f - value, 0f, 1f, 1f) :
new Vector4(0f, 0f, value, 1f);
}
}
else if (sprite != null && sprite.type == UISprite.Type.Filled)
{
sprite.fillDirection = UISprite.FillDirection.Vertical;
sprite.invert = isInverted;
sprite.fillAmount = value;
}
else
{
mFG.drawRegion = isInverted ?
new Vector4(0f, 1f - value, 1f, 1f) :
new Vector4(0f, 0f, 1f, value);
}
}
if (thumb != null && (mFG != null || mBG != null))
{
Vector3[] corners = (mFG != null) ? mFG.localCorners : mBG.localCorners;
Vector4 br = (mFG != null) ? mFG.border : mBG.border;
corners[0].x += br.x;
corners[1].x += br.x;
corners[2].x -= br.z;
corners[3].x -= br.z;
corners[0].y += br.y;
corners[1].y -= br.w;
corners[2].y -= br.w;
corners[3].y += br.y;
Transform t = (mFG != null) ? mFG.cachedTransform : mBG.cachedTransform;
for (int i = 0; i < 4; ++i) corners[i] = t.TransformPoint(corners[i]);
if (isHorizontal)
{
Vector3 v0 = Vector3.Lerp(corners[0], corners[1], 0.5f);
Vector3 v1 = Vector3.Lerp(corners[2], corners[3], 0.5f);
SetThumbPosition(Vector3.Lerp(v0, v1, isInverted ? 1f - value : value));
}
else
{
Vector3 v0 = Vector3.Lerp(corners[0], corners[3], 0.5f);
Vector3 v1 = Vector3.Lerp(corners[1], corners[2], 0.5f);
SetThumbPosition(Vector3.Lerp(v0, v1, isInverted ? 1f - value : value));
}
}
}
/// <summary>
/// Set the position of the thumb to the specified world coordinates.
/// </summary>
protected void SetThumbPosition (Vector3 worldPos)
{
Transform t = thumb.parent;
if (t != null)
{
worldPos = t.InverseTransformPoint(worldPos);
worldPos.x = Mathf.Round(worldPos.x);
worldPos.y = Mathf.Round(worldPos.y);
worldPos.z = 0f;
if (Vector3.Distance(thumb.localPosition, worldPos) > 0.001f)
thumb.localPosition = worldPos;
}
else if (Vector3.Distance(thumb.position, worldPos) > 0.00001f)
thumb.position = worldPos;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIProgressBar.cs
|
C#
|
asf20
| 9,979
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
#define USE_MECANIM
#endif
using UnityEngine;
using System.Collections.Generic;
using AnimationOrTween;
/// <summary>
/// Play the specified animation on click.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/Play Animation")]
public class UIPlayAnimation : MonoBehaviour
{
static public UIPlayAnimation current = null;
/// <summary>
/// Target animation to activate.
/// </summary>
public Animation target;
#if USE_MECANIM
/// <summary>
/// Target animator system.
/// </summary>
public Animator animator;
#endif
/// <summary>
/// Optional clip name, if the animation has more than one clip.
/// </summary>
public string clipName;
/// <summary>
/// Which event will trigger the animation.
/// </summary>
public Trigger trigger = Trigger.OnClick;
/// <summary>
/// Which direction to animate in.
/// </summary>
public Direction playDirection = Direction.Forward;
/// <summary>
/// Whether the animation's position will be reset on play or will continue from where it left off.
/// </summary>
public bool resetOnPlay = false;
/// <summary>
/// Whether the selected object (this button) will be cleared when the animation gets activated.
/// </summary>
public bool clearSelection = false;
/// <summary>
/// What to do if the target game object is currently disabled.
/// </summary>
public EnableCondition ifDisabledOnPlay = EnableCondition.DoNothing;
/// <summary>
/// What to do with the target when the animation finishes.
/// </summary>
public DisableCondition disableWhenFinished = DisableCondition.DoNotDisable;
/// <summary>
/// Event delegates called when the animation finishes.
/// </summary>
public List<EventDelegate> onFinished = new List<EventDelegate>();
// Deprecated functionality, kept for backwards compatibility
[HideInInspector][SerializeField] GameObject eventReceiver;
[HideInInspector][SerializeField] string callWhenFinished;
bool mStarted = false;
bool mActivated = false;
bool dragHighlight = false;
bool dualState { get { return trigger == Trigger.OnPress || trigger == Trigger.OnHover; } }
void Awake ()
{
UIButton btn = GetComponent<UIButton>();
if (btn != null) dragHighlight = btn.dragHighlight;
// Remove deprecated functionality if new one is used
if (eventReceiver != null && EventDelegate.IsValid(onFinished))
{
eventReceiver = null;
callWhenFinished = null;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
}
/// <summary>
/// Automatically find the necessary components.
/// </summary>
void Start ()
{
mStarted = true;
#if USE_MECANIM
// Automatically try to find the animator
if (target == null && animator == null)
{
animator = GetComponentInChildren<Animator>();
#if UNITY_EDITOR
if (animator != null) NGUITools.SetDirty(this);
#endif
}
if (animator != null)
{
// Ensure that the animator is disabled as we will be sampling it manually
if (animator.enabled) animator.enabled = false;
// Don't continue since we already have an animator to work with
return;
}
#endif // USE_MECANIM
if (target == null)
{
target = GetComponentInChildren<Animation>();
#if UNITY_EDITOR
if (target != null) NGUITools.SetDirty(this);
#endif
}
if (target != null && target.enabled)
target.enabled = false;
}
void OnEnable ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (mStarted) OnHover(UICamera.IsHighlighted(gameObject));
if (UICamera.currentTouch != null)
{
if (trigger == Trigger.OnPress || trigger == Trigger.OnPressTrue)
mActivated = (UICamera.currentTouch.pressed == gameObject);
if (trigger == Trigger.OnHover || trigger == Trigger.OnHoverTrue)
mActivated = (UICamera.currentTouch.current == gameObject);
}
UIToggle toggle = GetComponent<UIToggle>();
if (toggle != null) EventDelegate.Add(toggle.onChange, OnToggle);
}
void OnDisable ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
UIToggle toggle = GetComponent<UIToggle>();
if (toggle != null) EventDelegate.Remove(toggle.onChange, OnToggle);
}
void OnHover (bool isOver)
{
if (!enabled) return;
if ( trigger == Trigger.OnHover ||
(trigger == Trigger.OnHoverTrue && isOver) ||
(trigger == Trigger.OnHoverFalse && !isOver))
Play(isOver, dualState);
}
void OnPress (bool isPressed)
{
if (!enabled) return;
if ( trigger == Trigger.OnPress ||
(trigger == Trigger.OnPressTrue && isPressed) ||
(trigger == Trigger.OnPressFalse && !isPressed))
Play(isPressed, dualState);
}
void OnClick () { if (enabled && trigger == Trigger.OnClick) Play(true, false); }
void OnDoubleClick () { if (enabled && trigger == Trigger.OnDoubleClick) Play(true, false); }
void OnSelect (bool isSelected)
{
if (!enabled) return;
if (trigger == Trigger.OnSelect ||
(trigger == Trigger.OnSelectTrue && isSelected) ||
(trigger == Trigger.OnSelectFalse && !isSelected))
Play(isSelected, dualState);
}
void OnToggle ()
{
if (!enabled || UIToggle.current == null) return;
if (trigger == Trigger.OnActivate ||
(trigger == Trigger.OnActivateTrue && UIToggle.current.value) ||
(trigger == Trigger.OnActivateFalse && !UIToggle.current.value))
Play(UIToggle.current.value, dualState);
}
void OnDragOver ()
{
if (enabled && dualState)
{
if (UICamera.currentTouch.dragged == gameObject) Play(true, true);
else if (dragHighlight && trigger == Trigger.OnPress) Play(true, true);
}
}
void OnDragOut ()
{
if (enabled && dualState && UICamera.hoveredObject != gameObject)
Play(false, true);
}
void OnDrop (GameObject go)
{
if (enabled && trigger == Trigger.OnPress && UICamera.currentTouch.dragged != gameObject)
Play(false, true);
}
/// <summary>
/// Start playing the animation.
/// </summary>
public void Play (bool forward) { Play(forward, true); }
/// <summary>
/// Start playing the animation.
/// </summary>
public void Play (bool forward, bool onlyIfDifferent)
{
#if USE_MECANIM
if (target || animator)
#else
if (target)
#endif
{
if (onlyIfDifferent)
{
if (mActivated == forward) return;
mActivated = forward;
}
if (clearSelection && UICamera.selectedObject == gameObject)
UICamera.selectedObject = null;
int pd = -(int)playDirection;
Direction dir = forward ? playDirection : ((Direction)pd);
#if USE_MECANIM
ActiveAnimation anim = target ?
ActiveAnimation.Play(target, clipName, dir, ifDisabledOnPlay, disableWhenFinished) :
ActiveAnimation.Play(animator, clipName, dir, ifDisabledOnPlay, disableWhenFinished);
#else
ActiveAnimation anim = ActiveAnimation.Play(target, clipName, dir, ifDisabledOnPlay, disableWhenFinished);
#endif
if (anim != null)
{
if (resetOnPlay) anim.Reset();
for (int i = 0; i < onFinished.Count; ++i)
EventDelegate.Add(anim.onFinished, OnFinished, true);
}
}
}
/// <summary>
/// Callback triggered when each tween executed by this script finishes.
/// </summary>
void OnFinished ()
{
if (current == null)
{
current = this;
EventDelegate.Execute(onFinished);
// Legacy functionality
if (eventReceiver != null && !string.IsNullOrEmpty(callWhenFinished))
eventReceiver.SendMessage(callWhenFinished, SendMessageOptions.DontRequireReceiver);
eventReceiver = null;
current = null;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIPlayAnimation.cs
|
C#
|
asf20
| 7,592
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Attach this script to a popup list, the parent of a group of toggles, or to a toggle itself to save its state.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Saved Option")]
public class UISavedOption : MonoBehaviour
{
/// <summary>
/// PlayerPrefs-stored key for this option.
/// </summary>
public string keyName;
string key { get { return (string.IsNullOrEmpty(keyName)) ? "NGUI State: " + name : keyName; } }
UIPopupList mList;
UIToggle mCheck;
/// <summary>
/// Cache the components and register a listener callback.
/// </summary>
void Awake ()
{
mList = GetComponent<UIPopupList>();
mCheck = GetComponent<UIToggle>();
}
/// <summary>
/// Load and set the state of the toggles.
/// </summary>
void OnEnable ()
{
if (mList != null) EventDelegate.Add(mList.onChange, SaveSelection);
if (mCheck != null) EventDelegate.Add(mCheck.onChange, SaveState);
if (mList != null)
{
string s = PlayerPrefs.GetString(key);
if (!string.IsNullOrEmpty(s)) mList.value = s;
return;
}
if (mCheck != null)
{
mCheck.value = (PlayerPrefs.GetInt(key, 1) != 0);
}
else
{
string s = PlayerPrefs.GetString(key);
UIToggle[] toggles = GetComponentsInChildren<UIToggle>(true);
for (int i = 0, imax = toggles.Length; i < imax; ++i)
{
UIToggle ch = toggles[i];
ch.value = (ch.name == s);
}
}
}
/// <summary>
/// Save the state on destroy.
/// </summary>
void OnDisable ()
{
if (mCheck != null) EventDelegate.Remove(mCheck.onChange, SaveState);
if (mList != null) EventDelegate.Remove(mList.onChange, SaveSelection);
if (mCheck == null && mList == null)
{
UIToggle[] toggles = GetComponentsInChildren<UIToggle>(true);
for (int i = 0, imax = toggles.Length; i < imax; ++i)
{
UIToggle ch = toggles[i];
if (ch.value)
{
PlayerPrefs.SetString(key, ch.name);
break;
}
}
}
}
/// <summary>
/// Save the selection.
/// </summary>
public void SaveSelection () { PlayerPrefs.SetString(key, UIPopupList.current.value); }
/// <summary>
/// Save the state.
/// </summary>
public void SaveState () { PlayerPrefs.SetInt(key, UIToggle.current.value ? 1 : 0); }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UISavedOption.cs
|
C#
|
asf20
| 2,407
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Turns the popup list it's attached to into a language selection list.
/// </summary>
[RequireComponent(typeof(UIPopupList))]
[AddComponentMenu("NGUI/Interaction/Language Selection")]
public class LanguageSelection : MonoBehaviour
{
UIPopupList mList;
void Start ()
{
mList = GetComponent<UIPopupList>();
if (Localization.knownLanguages != null)
{
mList.items.Clear();
for (int i = 0, imax = Localization.knownLanguages.Length; i < imax; ++i)
mList.items.Add(Localization.knownLanguages[i]);
mList.value = Localization.language;
}
EventDelegate.Add(mList.onChange, OnChange);
}
void OnChange ()
{
Localization.language = UIPopupList.current.value;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/LanguageSelection.cs
|
C#
|
asf20
| 945
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This script makes it possible to resize the specified widget by dragging on the object this script is attached to.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Drag-Resize Widget")]
public class UIDragResize : MonoBehaviour
{
/// <summary>
/// Widget that will be dragged.
/// </summary>
public UIWidget target;
/// <summary>
/// Widget's pivot that will be dragged
/// </summary>
public UIWidget.Pivot pivot = UIWidget.Pivot.BottomRight;
/// <summary>
/// Minimum width the widget will be allowed to shrink to when resizing.
/// </summary>
public int minWidth = 100;
/// <summary>
/// Minimum height the widget will be allowed to shrink to when resizing.
/// </summary>
public int minHeight = 100;
/// <summary>
/// Maximum width the widget will be allowed to expand to when resizing.
/// </summary>
public int maxWidth = 100000;
/// <summary>
/// Maximum height the widget will be allowed to expand to when resizing.
/// </summary>
public int maxHeight = 100000;
Plane mPlane;
Vector3 mRayPos;
Vector3 mLocalPos;
int mWidth = 0;
int mHeight = 0;
bool mDragging = false;
/// <summary>
/// Start the dragging operation.
/// </summary>
void OnDragStart ()
{
if (target != null)
{
Vector3[] corners = target.worldCorners;
mPlane = new Plane(corners[0], corners[1], corners[3]);
Ray ray = UICamera.currentRay;
float dist;
if (mPlane.Raycast(ray, out dist))
{
mRayPos = ray.GetPoint(dist);
mLocalPos = target.cachedTransform.localPosition;
mWidth = target.width;
mHeight = target.height;
mDragging = true;
}
}
}
/// <summary>
/// Adjust the widget's dimensions.
/// </summary>
void OnDrag (Vector2 delta)
{
if (mDragging && target != null)
{
float dist;
Ray ray = UICamera.currentRay;
if (mPlane.Raycast(ray, out dist))
{
Transform t = target.cachedTransform;
t.localPosition = mLocalPos;
target.width = mWidth;
target.height = mHeight;
// Move the widget
Vector3 worldDelta = ray.GetPoint(dist) - mRayPos;
t.position = t.position + worldDelta;
// Calculate the final delta
Vector3 localDelta = Quaternion.Inverse(t.localRotation) * (t.localPosition - mLocalPos);
// Restore the position
t.localPosition = mLocalPos;
// Adjust the widget
NGUIMath.ResizeWidget(target, pivot, localDelta.x, localDelta.y, minWidth, minHeight, maxWidth, maxHeight);
}
}
}
/// <summary>
/// End the resize operation.
/// </summary>
void OnDragEnd () { mDragging = false; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIDragResize.cs
|
C#
|
asf20
| 2,769
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using AnimationOrTween;
using System.Collections.Generic;
/// <summary>
/// Play the specified tween on click.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/Play Tween")]
public class UIPlayTween : MonoBehaviour
{
static public UIPlayTween current;
/// <summary>
/// Target on which there is one or more tween.
/// </summary>
public GameObject tweenTarget;
/// <summary>
/// If there are multiple tweens, you can choose which ones get activated by changing their group.
/// </summary>
public int tweenGroup = 0;
/// <summary>
/// Which event will trigger the tween.
/// </summary>
public Trigger trigger = Trigger.OnClick;
/// <summary>
/// Direction to tween in.
/// </summary>
public Direction playDirection = Direction.Forward;
/// <summary>
/// Whether the tween will be reset to the start or end when activated. If not, it will continue from where it currently is.
/// </summary>
public bool resetOnPlay = false;
/// <summary>
/// Whether the tween will be reset to the start if it's disabled when activated.
/// </summary>
public bool resetIfDisabled = false;
/// <summary>
/// What to do if the tweenTarget game object is currently disabled.
/// </summary>
public EnableCondition ifDisabledOnPlay = EnableCondition.DoNothing;
/// <summary>
/// What to do with the tweenTarget after the tween finishes.
/// </summary>
public DisableCondition disableWhenFinished = DisableCondition.DoNotDisable;
/// <summary>
/// Whether the tweens on the child game objects will be considered.
/// </summary>
public bool includeChildren = false;
/// <summary>
/// Event delegates called when the animation finishes.
/// </summary>
public List<EventDelegate> onFinished = new List<EventDelegate>();
// Deprecated functionality, kept for backwards compatibility
[HideInInspector][SerializeField] GameObject eventReceiver;
[HideInInspector][SerializeField] string callWhenFinished;
UITweener[] mTweens;
bool mStarted = false;
int mActive = 0;
bool mActivated = false;
void Awake ()
{
// Remove deprecated functionality if new one is used
if (eventReceiver != null && EventDelegate.IsValid(onFinished))
{
eventReceiver = null;
callWhenFinished = null;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
}
void Start()
{
mStarted = true;
if (tweenTarget == null)
{
tweenTarget = gameObject;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
}
void OnEnable ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (mStarted) OnHover(UICamera.IsHighlighted(gameObject));
if (UICamera.currentTouch != null)
{
if (trigger == Trigger.OnPress || trigger == Trigger.OnPressTrue)
mActivated = (UICamera.currentTouch.pressed == gameObject);
if (trigger == Trigger.OnHover || trigger == Trigger.OnHoverTrue)
mActivated = (UICamera.currentTouch.current == gameObject);
}
UIToggle toggle = GetComponent<UIToggle>();
if (toggle != null) EventDelegate.Add(toggle.onChange, OnToggle);
}
void OnDisable ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
UIToggle toggle = GetComponent<UIToggle>();
if (toggle != null) EventDelegate.Remove(toggle.onChange, OnToggle);
}
void OnHover (bool isOver)
{
if (enabled)
{
if (trigger == Trigger.OnHover ||
(trigger == Trigger.OnHoverTrue && isOver) ||
(trigger == Trigger.OnHoverFalse && !isOver))
{
mActivated = isOver && (trigger == Trigger.OnHover);
Play(isOver);
}
}
}
void OnDragOut ()
{
if (enabled && mActivated)
{
mActivated = false;
Play(false);
}
}
void OnPress (bool isPressed)
{
if (enabled)
{
if (trigger == Trigger.OnPress ||
(trigger == Trigger.OnPressTrue && isPressed) ||
(trigger == Trigger.OnPressFalse && !isPressed))
{
mActivated = isPressed && (trigger == Trigger.OnPress);
Play(isPressed);
}
}
}
void OnClick ()
{
if (enabled && trigger == Trigger.OnClick)
{
Play(true);
}
}
void OnDoubleClick ()
{
if (enabled && trigger == Trigger.OnDoubleClick)
{
Play(true);
}
}
void OnSelect (bool isSelected)
{
if (enabled)
{
if (trigger == Trigger.OnSelect ||
(trigger == Trigger.OnSelectTrue && isSelected) ||
(trigger == Trigger.OnSelectFalse && !isSelected))
{
mActivated = isSelected && (trigger == Trigger.OnSelect);
Play(isSelected);
}
}
}
void OnToggle ()
{
if (!enabled || UIToggle.current == null) return;
if (trigger == Trigger.OnActivate ||
(trigger == Trigger.OnActivateTrue && UIToggle.current.value) ||
(trigger == Trigger.OnActivateFalse && !UIToggle.current.value))
Play(UIToggle.current.value);
}
void Update ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (disableWhenFinished != DisableCondition.DoNotDisable && mTweens != null)
{
bool isFinished = true;
bool properDirection = true;
for (int i = 0, imax = mTweens.Length; i < imax; ++i)
{
UITweener tw = mTweens[i];
if (tw.tweenGroup != tweenGroup) continue;
if (tw.enabled)
{
isFinished = false;
break;
}
else if ((int)tw.direction != (int)disableWhenFinished)
{
properDirection = false;
}
}
if (isFinished)
{
if (properDirection) NGUITools.SetActive(tweenTarget, false);
mTweens = null;
}
}
}
/// <summary>
/// Activate the tweeners.
/// </summary>
public void Play (bool forward)
{
mActive = 0;
GameObject go = (tweenTarget == null) ? gameObject : tweenTarget;
if (!NGUITools.GetActive(go))
{
// If the object is disabled, don't do anything
if (ifDisabledOnPlay != EnableCondition.EnableThenPlay) return;
// Enable the game object before tweening it
NGUITools.SetActive(go, true);
}
// Gather the tweening components
mTweens = includeChildren ? go.GetComponentsInChildren<UITweener>() : go.GetComponents<UITweener>();
if (mTweens.Length == 0)
{
// No tweeners found -- should we disable the object?
if (disableWhenFinished != DisableCondition.DoNotDisable)
NGUITools.SetActive(tweenTarget, false);
}
else
{
bool activated = false;
if (playDirection == Direction.Reverse) forward = !forward;
// Run through all located tween components
for (int i = 0, imax = mTweens.Length; i < imax; ++i)
{
UITweener tw = mTweens[i];
// If the tweener's group matches, we can work with it
if (tw.tweenGroup == tweenGroup)
{
// Ensure that the game objects are enabled
if (!activated && !NGUITools.GetActive(go))
{
activated = true;
NGUITools.SetActive(go, true);
}
++mActive;
// Toggle or activate the tween component
if (playDirection == Direction.Toggle)
{
// Listen for tween finished messages
EventDelegate.Add(tw.onFinished, OnFinished, true);
tw.Toggle();
}
else
{
if (resetOnPlay || (resetIfDisabled && !tw.enabled)) tw.ResetToBeginning();
// Listen for tween finished messages
EventDelegate.Add(tw.onFinished, OnFinished, true);
tw.Play(forward);
}
}
}
}
}
/// <summary>
/// Callback triggered when each tween executed by this script finishes.
/// </summary>
void OnFinished ()
{
if (--mActive == 0 && current == null)
{
current = this;
EventDelegate.Execute(onFinished);
// Legacy functionality
if (eventReceiver != null && !string.IsNullOrEmpty(callWhenFinished))
eventReceiver.SendMessage(callWhenFinished, SendMessageOptions.DontRequireReceiver);
eventReceiver = null;
current = null;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIPlayTween.cs
|
C#
|
asf20
| 7,829
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// All children added to the game object with this script will be repositioned to be on a grid of specified dimensions.
/// If you want the cells to automatically set their scale based on the dimensions of their content, take a look at UITable.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Grid")]
public class UIGrid : UIWidgetContainer
{
public delegate void OnReposition ();
public enum Arrangement
{
Horizontal,
Vertical,
}
public enum Sorting
{
None,
Alphabetic,
Horizontal,
Vertical,
Custom,
}
/// <summary>
/// Type of arrangement -- vertical or horizontal.
/// </summary>
public Arrangement arrangement = Arrangement.Horizontal;
/// <summary>
/// How to sort the grid's elements.
/// </summary>
public Sorting sorting = Sorting.None;
/// <summary>
/// Final pivot point for the grid's content.
/// </summary>
public UIWidget.Pivot pivot = UIWidget.Pivot.TopLeft;
/// <summary>
/// Maximum children per line.
/// If the arrangement is horizontal, this denotes the number of columns.
/// If the arrangement is vertical, this stands for the number of rows.
/// </summary>
public int maxPerLine = 0;
/// <summary>
/// The width of each of the cells.
/// </summary>
public float cellWidth = 200f;
/// <summary>
/// The height of each of the cells.
/// </summary>
public float cellHeight = 200f;
/// <summary>
/// Whether the grid will smoothly animate its children into the correct place.
/// </summary>
public bool animateSmoothly = false;
/// <summary>
/// Whether to ignore the disabled children or to treat them as being present.
/// </summary>
public bool hideInactive = true;
/// <summary>
/// Whether the parent container will be notified of the grid's changes.
/// </summary>
public bool keepWithinPanel = false;
/// <summary>
/// Callback triggered when the grid repositions its contents.
/// </summary>
public OnReposition onReposition;
/// <summary>
/// Custom sort delegate, used when the sorting method is set to 'custom'.
/// </summary>
public BetterList<Transform>.CompareFunc onCustomSort;
// Use the 'sorting' property instead
[HideInInspector][SerializeField] bool sorted = false;
protected bool mReposition = false;
protected UIPanel mPanel;
protected bool mInitDone = false;
/// <summary>
/// Reposition the children on the next Update().
/// </summary>
public bool repositionNow { set { if (value) { mReposition = true; enabled = true; } } }
/// <summary>
/// Get the current list of the grid's children.
/// </summary>
public BetterList<Transform> GetChildList()
{
Transform myTrans = transform;
BetterList<Transform> list = new BetterList<Transform>();
for (int i = 0; i < myTrans.childCount; ++i)
{
Transform t = myTrans.GetChild(i);
if (!hideInactive || (t && NGUITools.GetActive(t.gameObject)))
list.Add(t);
}
return list;
}
/// <summary>
/// Convenience method: get the child at the specified index.
/// Note that if you plan on calling this function more than once, it's faster to get the entire list using GetChildList() instead.
/// </summary>
public Transform GetChild (int index)
{
BetterList<Transform> list = GetChildList();
return (index < list.size) ? list[index] : null;
}
/// <summary>
/// Convenience method -- add a new child.
/// </summary>
public void AddChild (Transform trans) { AddChild(trans, true); }
/// <summary>
/// Convenience method -- add a new child.
/// Note that if you plan on adding multiple objects, it's faster to GetChildList() and modify that instead.
/// </summary>
public void AddChild (Transform trans, bool sort)
{
if (trans != null)
{
BetterList<Transform> list = GetChildList();
list.Add(trans);
ResetPosition(list);
}
}
/// <summary>
/// Convenience method -- add a new child at the specified index.
/// Note that if you plan on adding multiple objects, it's faster to GetChildList() and modify that instead.
/// </summary>
public void AddChild (Transform trans, int index)
{
if (trans != null)
{
if (sorting != Sorting.None)
Debug.LogWarning("The Grid has sorting enabled, so AddChild at index may not work as expected.", this);
BetterList<Transform> list = GetChildList();
list.Insert(index, trans);
ResetPosition(list);
}
}
/// <summary>
/// Convenience method -- remove a child at the specified index.
/// Note that if you plan on removing multiple objects, it's faster to GetChildList() and modify that instead.
/// </summary>
public Transform RemoveChild (int index)
{
BetterList<Transform> list = GetChildList();
if (index < list.size)
{
Transform t = list[index];
list.RemoveAt(index);
ResetPosition(list);
return t;
}
return null;
}
/// <summary>
/// Remove the specified child from the list.
/// Note that if you plan on removing multiple objects, it's faster to GetChildList() and modify that instead.
/// </summary>
public bool RemoveChild (Transform t)
{
BetterList<Transform> list = GetChildList();
if (list.Remove(t))
{
ResetPosition(list);
return true;
}
return false;
}
/// <summary>
/// Initialize the grid. Executed only once.
/// </summary>
protected virtual void Init ()
{
mInitDone = true;
mPanel = NGUITools.FindInParents<UIPanel>(gameObject);
}
/// <summary>
/// Cache everything and reset the initial position of all children.
/// </summary>
protected virtual void Start ()
{
if (!mInitDone) Init();
bool smooth = animateSmoothly;
animateSmoothly = false;
Reposition();
animateSmoothly = smooth;
enabled = false;
}
/// <summary>
/// Reset the position if necessary, then disable the component.
/// </summary>
protected virtual void Update ()
{
if (mReposition) Reposition();
enabled = false;
}
// Various generic sorting functions
static public int SortByName (Transform a, Transform b) { return string.Compare(a.name, b.name); }
static public int SortHorizontal (Transform a, Transform b) { return a.localPosition.x.CompareTo(b.localPosition.x); }
static public int SortVertical (Transform a, Transform b) { return b.localPosition.y.CompareTo(a.localPosition.y); }
/// <summary>
/// You can override this function, but in most cases it's easier to just set the onCustomSort delegate instead.
/// </summary>
protected virtual void Sort (BetterList<Transform> list) { }
/// <summary>
/// Recalculate the position of all elements within the grid, sorting them alphabetically if necessary.
/// </summary>
[ContextMenu("Execute")]
public virtual void Reposition ()
{
if (Application.isPlaying && !mInitDone && NGUITools.GetActive(this))
{
mReposition = true;
return;
}
// Legacy functionality
if (sorted)
{
sorted = false;
if (sorting == Sorting.None)
sorting = Sorting.Alphabetic;
NGUITools.SetDirty(this);
}
if (!mInitDone) Init();
// Get the list of children in their current order
BetterList<Transform> list = GetChildList();
// Sort the list using the desired sorting logic
if (sorting != Sorting.None)
{
if (sorting == Sorting.Alphabetic) list.Sort(SortByName);
else if (sorting == Sorting.Horizontal) list.Sort(SortHorizontal);
else if (sorting == Sorting.Vertical) list.Sort(SortVertical);
else if (onCustomSort != null) list.Sort(onCustomSort);
else Sort(list);
}
// Reset the position and order of all objects in the list
ResetPosition(list);
// Constrain everything to be within the panel's bounds
if (keepWithinPanel) ConstrainWithinPanel();
// Notify the listener
if (onReposition != null)
onReposition();
}
/// <summary>
/// Constrain the grid's content to be within the panel's bounds.
/// </summary>
public void ConstrainWithinPanel ()
{
if (mPanel != null)
mPanel.ConstrainTargetToBounds(transform, true);
}
/// <summary>
/// Reset the position of all child objects based on the order of items in the list.
/// </summary>
protected void ResetPosition (BetterList<Transform> list)
{
mReposition = false;
// Epic hack: Unparent all children so that we get to control the order in which they are re-added back in
for (int i = 0, imax = list.size; i < imax; ++i)
list[i].parent = null;
int x = 0;
int y = 0;
int maxX = 0;
int maxY = 0;
Transform myTrans = transform;
// Re-add the children in the same order we have them in and position them accordingly
for (int i = 0, imax = list.size; i < imax; ++i)
{
Transform t = list[i];
t.parent = myTrans;
float depth = t.localPosition.z;
Vector3 pos = (arrangement == Arrangement.Horizontal) ?
new Vector3(cellWidth * x, -cellHeight * y, depth) :
new Vector3(cellWidth * y, -cellHeight * x, depth);
if (animateSmoothly && Application.isPlaying)
{
SpringPosition.Begin(t.gameObject, pos, 15f).updateScrollView = true;
}
else t.localPosition = pos;
maxX = Mathf.Max(maxX, x);
maxY = Mathf.Max(maxY, y);
if (++x >= maxPerLine && maxPerLine > 0)
{
x = 0;
++y;
}
}
// Apply the origin offset
if (pivot != UIWidget.Pivot.TopLeft)
{
Vector2 po = NGUIMath.GetPivotOffset(pivot);
float fx, fy;
if (arrangement == Arrangement.Horizontal)
{
fx = Mathf.Lerp(0f, maxX * cellWidth, po.x);
fy = Mathf.Lerp(-maxY * cellHeight, 0f, po.y);
}
else
{
fx = Mathf.Lerp(0f, maxY * cellWidth, po.x);
fy = Mathf.Lerp(-maxX * cellHeight, 0f, po.y);
}
for (int i = 0; i < myTrans.childCount; ++i)
{
Transform t = myTrans.GetChild(i);
SpringPosition sp = t.GetComponent<SpringPosition>();
if (sp != null)
{
sp.target.x -= fx;
sp.target.y -= fy;
}
else
{
Vector3 pos = t.localPosition;
pos.x -= fx;
pos.y -= fy;
t.localPosition = pos;
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIGrid.cs
|
C#
|
asf20
| 10,079
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Ever wanted to be able to auto-center on an object within a draggable panel?
/// Attach this script to the container that has the objects to center on as its children.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Center Scroll View on Child")]
public class UICenterOnChild : MonoBehaviour
{
/// <summary>
/// The strength of the spring.
/// </summary>
public float springStrength = 8f;
/// <summary>
/// If set to something above zero, it will be possible to move to the next page after dragging past the specified threshold.
/// </summary>
public float nextPageThreshold = 0f;
/// <summary>
/// Callback to be triggered when the centering operation completes.
/// </summary>
public SpringPanel.OnFinished onFinished;
UIScrollView mScrollView;
GameObject mCenteredObject;
/// <summary>
/// Game object that the draggable panel is currently centered on.
/// </summary>
public GameObject centeredObject { get { return mCenteredObject; } }
void OnEnable () { Recenter(); }
void OnDragFinished () { if (enabled) Recenter(); }
/// <summary>
/// Ensure that the threshold is always positive.
/// </summary>
void OnValidate ()
{
nextPageThreshold = Mathf.Abs(nextPageThreshold);
}
/// <summary>
/// Recenter the draggable list on the center-most child.
/// </summary>
public void Recenter ()
{
if (mScrollView == null)
{
mScrollView = NGUITools.FindInParents<UIScrollView>(gameObject);
if (mScrollView == null)
{
Debug.LogWarning(GetType() + " requires " + typeof(UIScrollView) + " on a parent object in order to work", this);
enabled = false;
return;
}
else
{
mScrollView.onDragFinished = OnDragFinished;
if (mScrollView.horizontalScrollBar != null)
mScrollView.horizontalScrollBar.onDragFinished = OnDragFinished;
if (mScrollView.verticalScrollBar != null)
mScrollView.verticalScrollBar.onDragFinished = OnDragFinished;
}
}
if (mScrollView.panel == null) return;
// Calculate the panel's center in world coordinates
Vector3[] corners = mScrollView.panel.worldCorners;
Vector3 panelCenter = (corners[2] + corners[0]) * 0.5f;
// Offset this value by the momentum
Vector3 pickingPoint = panelCenter - mScrollView.currentMomentum * (mScrollView.momentumAmount * 0.1f);
mScrollView.currentMomentum = Vector3.zero;
float min = float.MaxValue;
Transform closest = null;
Transform trans = transform;
int index = 0;
// Determine the closest child
for (int i = 0, imax = trans.childCount; i < imax; ++i)
{
Transform t = trans.GetChild(i);
float sqrDist = Vector3.SqrMagnitude(t.position - pickingPoint);
if (sqrDist < min)
{
min = sqrDist;
closest = t;
index = i;
}
}
// If we have a touch in progress and the next page threshold set
if (nextPageThreshold > 0f && UICamera.currentTouch != null)
{
// If we're still on the same object
if (mCenteredObject != null && mCenteredObject.transform == trans.GetChild(index))
{
Vector2 totalDelta = UICamera.currentTouch.totalDelta;
float delta = 0f;
switch (mScrollView.movement)
{
case UIScrollView.Movement.Horizontal:
{
delta = totalDelta.x;
break;
}
case UIScrollView.Movement.Vertical:
{
delta = totalDelta.y;
break;
}
default:
{
delta = totalDelta.magnitude;
break;
}
}
if (delta > nextPageThreshold)
{
// Next page
if (index > 0)
closest = trans.GetChild(index - 1);
}
else if (delta < -nextPageThreshold)
{
// Previous page
if (index < trans.childCount - 1)
closest = trans.GetChild(index + 1);
}
}
}
CenterOn(closest, panelCenter);
}
/// <summary>
/// Center the panel on the specified target.
/// </summary>
void CenterOn (Transform target, Vector3 panelCenter)
{
if (target != null && mScrollView != null && mScrollView.panel != null)
{
Transform panelTrans = mScrollView.panel.cachedTransform;
mCenteredObject = target.gameObject;
// Figure out the difference between the chosen child and the panel's center in local coordinates
Vector3 cp = panelTrans.InverseTransformPoint(target.position);
Vector3 cc = panelTrans.InverseTransformPoint(panelCenter);
Vector3 localOffset = cp - cc;
// Offset shouldn't occur if blocked
if (!mScrollView.canMoveHorizontally) localOffset.x = 0f;
if (!mScrollView.canMoveVertically) localOffset.y = 0f;
localOffset.z = 0f;
// Spring the panel to this calculated position
SpringPanel.Begin(mScrollView.panel.cachedGameObject,
panelTrans.localPosition - localOffset, springStrength).onFinished = onFinished;
}
else mCenteredObject = null;
}
/// <summary>
/// Center the panel on the specified target.
/// </summary>
public void CenterOn (Transform target)
{
if (mScrollView != null && mScrollView.panel != null)
{
Vector3[] corners = mScrollView.panel.worldCorners;
Vector3 panelCenter = (corners[2] + corners[0]) * 0.5f;
CenterOn(target, panelCenter);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UICenterOnChild.cs
|
C#
|
asf20
| 5,296
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This class makes it possible to activate or select something by pressing a key (such as space bar for example).
/// </summary>
[AddComponentMenu("Game/UI/Key Binding")]
public class UIKeyBinding : MonoBehaviour
{
public enum Action
{
PressAndClick,
Select,
}
public enum Modifier
{
None,
Shift,
Control,
Alt,
}
/// <summary>
/// Key that will trigger the binding.
/// </summary>
public KeyCode keyCode = KeyCode.None;
/// <summary>
/// Modifier key that must be active in order for the binding to trigger.
/// </summary>
public Modifier modifier = Modifier.None;
/// <summary>
/// Action to take with the specified key.
/// </summary>
public Action action = Action.PressAndClick;
bool mIgnoreUp = false;
bool mIsInput = false;
/// <summary>
/// If we're bound to an input field, subscribe to its Submit notification.
/// </summary>
void Start ()
{
UIInput input = GetComponent<UIInput>();
mIsInput = (input != null);
if (input != null) EventDelegate.Add(input.onSubmit, OnSubmit);
}
/// <summary>
/// Ignore the KeyUp message if the input field "ate" it.
/// </summary>
void OnSubmit () { if (UICamera.currentKey == keyCode && IsModifierActive()) mIgnoreUp = true; }
/// <summary>
/// Convenience function that checks whether the required modifier key is active.
/// </summary>
bool IsModifierActive ()
{
if (modifier == Modifier.None) return true;
if (modifier == Modifier.Alt)
{
if (Input.GetKey(KeyCode.LeftAlt) ||
Input.GetKey(KeyCode.RightAlt)) return true;
}
else if (modifier == Modifier.Control)
{
if (Input.GetKey(KeyCode.LeftControl) ||
Input.GetKey(KeyCode.RightControl)) return true;
}
else if (modifier == Modifier.Shift)
{
if (Input.GetKey(KeyCode.LeftShift) ||
Input.GetKey(KeyCode.RightShift)) return true;
}
return false;
}
/// <summary>
/// Process the key binding.
/// </summary>
void Update ()
{
if (keyCode == KeyCode.None || !IsModifierActive()) return;
if (action == Action.PressAndClick)
{
if (UICamera.inputHasFocus) return;
UICamera.currentTouch = UICamera.controller;
UICamera.currentScheme = UICamera.ControlScheme.Mouse;
UICamera.currentTouch.current = gameObject;
if (Input.GetKeyDown(keyCode))
{
UICamera.Notify(gameObject, "OnPress", true);
}
if (Input.GetKeyUp(keyCode))
{
UICamera.Notify(gameObject, "OnPress", false);
UICamera.Notify(gameObject, "OnClick", null);
}
UICamera.currentTouch.current = null;
}
else if (action == Action.Select)
{
if (Input.GetKeyUp(keyCode))
{
if (mIsInput)
{
if (!mIgnoreUp && !UICamera.inputHasFocus)
{
UICamera.selectedObject = gameObject;
}
mIgnoreUp = false;
}
else
{
UICamera.selectedObject = gameObject;
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIKeyBinding.cs
|
C#
|
asf20
| 3,055
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Popup list can be used to display pop-up menus and drop-down lists.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/Popup List")]
public class UIPopupList : UIWidgetContainer
{
/// <summary>
/// Current popup list. Only available during the OnSelectionChange event callback.
/// </summary>
static public UIPopupList current;
const float animSpeed = 0.15f;
public enum Position
{
Auto,
Above,
Below,
}
/// <summary>
/// Atlas used by the sprites.
/// </summary>
public UIAtlas atlas;
/// <summary>
/// Font used by the labels.
/// </summary>
public UIFont bitmapFont;
/// <summary>
/// True type font used by the labels. Alternative to specifying a bitmap font ('font').
/// </summary>
public Font trueTypeFont;
/// <summary>
/// Font used by the popup list. Conveniently wraps both dynamic and bitmap fonts into one property.
/// </summary>
public Object ambigiousFont
{
get
{
if (trueTypeFont != null) return trueTypeFont;
if (bitmapFont != null) return bitmapFont;
return font;
}
set
{
if (value is Font)
{
trueTypeFont = value as Font;
bitmapFont = null;
font = null;
}
else if (value is UIFont)
{
bitmapFont = value as UIFont;
trueTypeFont = null;
font = null;
}
}
}
/// <summary>
/// Size of the font to use for the popup list's labels.
/// </summary>
public int fontSize = 16;
/// <summary>
/// Font style used by the dynamic font.
/// </summary>
public FontStyle fontStyle = FontStyle.Normal;
/// <summary>
/// Name of the sprite used to create the popup's background.
/// </summary>
public string backgroundSprite;
/// <summary>
/// Name of the sprite used to highlight items.
/// </summary>
public string highlightSprite;
/// <summary>
/// Popup list's display style.
/// </summary>
public Position position = Position.Auto;
/// <summary>
/// New line-delimited list of items.
/// </summary>
public List<string> items = new List<string>();
/// <summary>
/// Amount of padding added to labels.
/// </summary>
public Vector2 padding = new Vector3(4f, 4f);
/// <summary>
/// Color tint applied to labels inside the list.
/// </summary>
public Color textColor = Color.white;
/// <summary>
/// Color tint applied to the background.
/// </summary>
public Color backgroundColor = Color.white;
/// <summary>
/// Color tint applied to the highlighter.
/// </summary>
public Color highlightColor = new Color(225f / 255f, 200f / 255f, 150f / 255f, 1f);
/// <summary>
/// Whether the popup list is animated or not. Disable for better performance.
/// </summary>
public bool isAnimated = true;
/// <summary>
/// Whether the popup list's values will be localized.
/// </summary>
public bool isLocalized = false;
/// <summary>
/// Callbacks triggered when the popup list gets a new item selection.
/// </summary>
public List<EventDelegate> onChange = new List<EventDelegate>();
// Currently selected item
[HideInInspector][SerializeField] string mSelectedItem;
UIPanel mPanel;
GameObject mChild;
UISprite mBackground;
UISprite mHighlight;
UILabel mHighlightedLabel = null;
List<UILabel> mLabelList = new List<UILabel>();
float mBgBorder = 0f;
// Deprecated functionality
[HideInInspector][SerializeField] GameObject eventReceiver;
[HideInInspector][SerializeField] string functionName = "OnSelectionChange";
[HideInInspector][SerializeField] float textScale = 0f;
[HideInInspector][SerializeField] UIFont font; // Use 'bitmapFont' instead
// This functionality is no longer needed as the same can be achieved by choosing a
// OnValueChange notification targeting a label's SetCurrentSelection function.
// If your code was list.textLabel = myLabel, change it to:
// EventDelegate.Add(list.onChange, lbl.SetCurrentSelection);
[HideInInspector][SerializeField] UILabel textLabel;
public delegate void LegacyEvent (string val);
LegacyEvent mLegacyEvent;
[System.Obsolete("Use EventDelegate.Add(popup.onChange, YourCallback) instead, and UIPopupList.current.value to determine the state")]
public LegacyEvent onSelectionChange { get { return mLegacyEvent; } set { mLegacyEvent = value; } }
/// <summary>
/// Whether the popup list is currently open.
/// </summary>
public bool isOpen { get { return mChild != null; } }
/// <summary>
/// Current selection.
/// </summary>
public string value
{
get
{
return mSelectedItem;
}
set
{
mSelectedItem = value;
if (mSelectedItem == null) return;
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (mSelectedItem != null)
TriggerCallbacks();
}
}
[System.Obsolete("Use 'value' instead")]
public string selection { get { return value; } set { this.value = value; } }
/// <summary>
/// Whether the popup list will be handling keyboard, joystick and controller events.
/// </summary>
bool handleEvents
{
get
{
UIKeyNavigation keys = GetComponent<UIKeyNavigation>();
return (keys == null || !keys.enabled);
}
set
{
UIKeyNavigation keys = GetComponent<UIKeyNavigation>();
if (keys != null) keys.enabled = !value;
}
}
/// <summary>
/// Whether the popup list is actually usable.
/// </summary>
bool isValid { get { return bitmapFont != null || trueTypeFont != null; } }
/// <summary>
/// Active font size.
/// </summary>
int activeFontSize { get { return (trueTypeFont != null || bitmapFont == null) ? fontSize : bitmapFont.defaultSize; } }
/// <summary>
/// Font scale applied to the popup list's text.
/// </summary>
float activeFontScale { get { return (trueTypeFont != null || bitmapFont == null) ? 1f : (float)fontSize / bitmapFont.defaultSize; } }
/// <summary>
/// Trigger all event notification callbacks.
/// </summary>
protected void TriggerCallbacks ()
{
if (current != this)
{
UIPopupList old = current;
current = this;
// Legacy functionality
if (mLegacyEvent != null) mLegacyEvent(mSelectedItem);
if (EventDelegate.IsValid(onChange))
{
EventDelegate.Execute(onChange);
}
else if (eventReceiver != null && !string.IsNullOrEmpty(functionName))
{
// Legacy functionality support (for backwards compatibility)
eventReceiver.SendMessage(functionName, mSelectedItem, SendMessageOptions.DontRequireReceiver);
}
current = old;
}
}
/// <summary>
/// Remove legacy functionality.
/// </summary>
void OnEnable ()
{
if (EventDelegate.IsValid(onChange))
{
eventReceiver = null;
functionName = null;
}
// 'font' is no longer used
if (font != null)
{
if (font.isDynamic)
{
trueTypeFont = font.dynamicFont;
fontStyle = font.dynamicFontStyle;
mUseDynamicFont = true;
}
else if (bitmapFont == null)
{
bitmapFont = font;
mUseDynamicFont = false;
}
font = null;
}
// 'textScale' is no longer used
if (textScale != 0f)
{
fontSize = (bitmapFont != null) ? Mathf.RoundToInt(bitmapFont.defaultSize * textScale) : 16;
textScale = 0f;
}
// Auto-upgrade to the true type font
if (trueTypeFont == null && bitmapFont != null && bitmapFont.isDynamic)
{
trueTypeFont = bitmapFont.dynamicFont;
bitmapFont = null;
}
}
bool mUseDynamicFont = false;
void OnValidate ()
{
Font ttf = trueTypeFont;
UIFont fnt = bitmapFont;
bitmapFont = null;
trueTypeFont = null;
if (ttf != null && (fnt == null || !mUseDynamicFont))
{
bitmapFont = null;
trueTypeFont = ttf;
mUseDynamicFont = true;
}
else if (fnt != null)
{
// Auto-upgrade from 3.0.2 and earlier
if (fnt.isDynamic)
{
trueTypeFont = fnt.dynamicFont;
fontStyle = fnt.dynamicFontStyle;
fontSize = fnt.defaultSize;
mUseDynamicFont = true;
}
else
{
bitmapFont = fnt;
mUseDynamicFont = false;
}
}
else
{
trueTypeFont = ttf;
mUseDynamicFont = true;
}
}
/// <summary>
/// Send out the selection message on start.
/// </summary>
void Start ()
{
// Auto-upgrade legacy functionality
if (textLabel != null)
{
EventDelegate.Add(onChange, textLabel.SetCurrentSelection);
textLabel = null;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
if (Application.isPlaying)
{
// Automatically choose the first item
if (string.IsNullOrEmpty(mSelectedItem))
{
if (items.Count > 0) value = items[0];
}
else
{
string s = mSelectedItem;
mSelectedItem = null;
value = s;
}
}
}
/// <summary>
/// Localize the text label.
/// </summary>
void OnLocalize () { if (isLocalized) TriggerCallbacks(); }
/// <summary>
/// Visibly highlight the specified transform by moving the highlight sprite to be over it.
/// </summary>
void Highlight (UILabel lbl, bool instant)
{
if (mHighlight != null)
{
// Don't allow highlighting while the label is animating to its intended position
TweenPosition tp = lbl.GetComponent<TweenPosition>();
if (tp != null && tp.enabled) return;
mHighlightedLabel = lbl;
UISpriteData sp = mHighlight.GetAtlasSprite();
if (sp == null) return;
float scaleFactor = atlas.pixelSize;
float offsetX = sp.borderLeft * scaleFactor;
float offsetY = sp.borderTop * scaleFactor;
Vector3 pos = lbl.cachedTransform.localPosition + new Vector3(-offsetX, offsetY, 1f);
if (instant || !isAnimated)
{
mHighlight.cachedTransform.localPosition = pos;
}
else
{
TweenPosition.Begin(mHighlight.gameObject, 0.1f, pos).method = UITweener.Method.EaseOut;
}
}
}
/// <summary>
/// Event function triggered when the mouse hovers over an item.
/// </summary>
void OnItemHover (GameObject go, bool isOver)
{
if (isOver)
{
UILabel lbl = go.GetComponent<UILabel>();
Highlight(lbl, false);
}
}
/// <summary>
/// Select the specified label.
/// </summary>
void Select (UILabel lbl, bool instant)
{
Highlight(lbl, instant);
UIEventListener listener = lbl.gameObject.GetComponent<UIEventListener>();
value = listener.parameter as string;
UIPlaySound[] sounds = GetComponents<UIPlaySound>();
for (int i = 0, imax = sounds.Length; i < imax; ++i)
{
UIPlaySound snd = sounds[i];
if (snd.trigger == UIPlaySound.Trigger.OnClick)
{
NGUITools.PlaySound(snd.audioClip, snd.volume, 1f);
}
}
}
/// <summary>
/// Event function triggered when the drop-down list item gets clicked on.
/// </summary>
void OnItemPress (GameObject go, bool isPressed) { if (isPressed) Select(go.GetComponent<UILabel>(), true); }
/// <summary>
/// React to key-based input.
/// </summary>
void OnKey (KeyCode key)
{
if (enabled && NGUITools.GetActive(gameObject) && handleEvents)
{
int index = mLabelList.IndexOf(mHighlightedLabel);
if (index == -1) index = 0;
if (key == KeyCode.UpArrow)
{
if (index > 0)
{
Select(mLabelList[--index], false);
}
}
else if (key == KeyCode.DownArrow)
{
if (index + 1 < mLabelList.Count)
{
Select(mLabelList[++index], false);
}
}
else if (key == KeyCode.Escape)
{
OnSelect(false);
}
}
}
/// <summary>
/// Get rid of the popup dialog when the selection gets lost.
/// </summary>
void OnSelect (bool isSelected) { if (!isSelected) Close(); }
/// <summary>
/// Manually close the popup list.
/// </summary>
public void Close ()
{
if (mChild != null)
{
mLabelList.Clear();
handleEvents = false;
if (isAnimated)
{
UIWidget[] widgets = mChild.GetComponentsInChildren<UIWidget>();
for (int i = 0, imax = widgets.Length; i < imax; ++i)
{
UIWidget w = widgets[i];
Color c = w.color;
c.a = 0f;
TweenColor.Begin(w.gameObject, animSpeed, c).method = UITweener.Method.EaseOut;
}
Collider[] cols = mChild.GetComponentsInChildren<Collider>();
for (int i = 0, imax = cols.Length; i < imax; ++i) cols[i].enabled = false;
Destroy(mChild, animSpeed);
}
else Destroy(mChild);
mBackground = null;
mHighlight = null;
mChild = null;
}
}
/// <summary>
/// Helper function that causes the widget to smoothly fade in.
/// </summary>
void AnimateColor (UIWidget widget)
{
Color c = widget.color;
widget.color = new Color(c.r, c.g, c.b, 0f);
TweenColor.Begin(widget.gameObject, animSpeed, c).method = UITweener.Method.EaseOut;
}
/// <summary>
/// Helper function that causes the widget to smoothly move into position.
/// </summary>
void AnimatePosition (UIWidget widget, bool placeAbove, float bottom)
{
Vector3 target = widget.cachedTransform.localPosition;
Vector3 start = placeAbove ? new Vector3(target.x, bottom, target.z) : new Vector3(target.x, 0f, target.z);
widget.cachedTransform.localPosition = start;
GameObject go = widget.gameObject;
TweenPosition.Begin(go, animSpeed, target).method = UITweener.Method.EaseOut;
}
/// <summary>
/// Helper function that causes the widget to smoothly grow until it reaches its original size.
/// </summary>
void AnimateScale (UIWidget widget, bool placeAbove, float bottom)
{
GameObject go = widget.gameObject;
Transform t = widget.cachedTransform;
float minHeight = activeFontSize * activeFontScale + mBgBorder * 2f;
t.localScale = new Vector3(1f, minHeight / widget.height, 1f);
TweenScale.Begin(go, animSpeed, Vector3.one).method = UITweener.Method.EaseOut;
if (placeAbove)
{
Vector3 pos = t.localPosition;
t.localPosition = new Vector3(pos.x, pos.y - widget.height + minHeight, pos.z);
TweenPosition.Begin(go, animSpeed, pos).method = UITweener.Method.EaseOut;
}
}
/// <summary>
/// Helper function used to animate widgets.
/// </summary>
void Animate (UIWidget widget, bool placeAbove, float bottom)
{
AnimateColor(widget);
AnimatePosition(widget, placeAbove, bottom);
}
/// <summary>
/// Display the drop-down list when the game object gets clicked on.
/// </summary>
void OnClick()
{
if (enabled && NGUITools.GetActive(gameObject) && mChild == null && atlas != null && isValid && items.Count > 0)
{
mLabelList.Clear();
// Automatically locate the panel responsible for this object
if (mPanel == null)
{
mPanel = UIPanel.Find(transform);
if (mPanel == null) return;
}
// Disable the navigation script
handleEvents = true;
// Calculate the dimensions of the object triggering the popup list so we can position it below it
Transform myTrans = transform;
Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(myTrans.parent, myTrans);
// Create the root object for the list
mChild = new GameObject("Drop-down List");
mChild.layer = gameObject.layer;
Transform t = mChild.transform;
t.parent = myTrans.parent;
t.localPosition = bounds.min;
t.localRotation = Quaternion.identity;
t.localScale = Vector3.one;
// Add a sprite for the background
mBackground = NGUITools.AddSprite(mChild, atlas, backgroundSprite);
mBackground.pivot = UIWidget.Pivot.TopLeft;
mBackground.depth = NGUITools.CalculateNextDepth(mPanel.gameObject);
mBackground.color = backgroundColor;
// We need to know the size of the background sprite for padding purposes
Vector4 bgPadding = mBackground.border;
mBgBorder = bgPadding.y;
mBackground.cachedTransform.localPosition = new Vector3(0f, bgPadding.y, 0f);
// Add a sprite used for the selection
mHighlight = NGUITools.AddSprite(mChild, atlas, highlightSprite);
mHighlight.pivot = UIWidget.Pivot.TopLeft;
mHighlight.color = highlightColor;
UISpriteData hlsp = mHighlight.GetAtlasSprite();
if (hlsp == null) return;
float hlspHeight = hlsp.borderTop;
float fontHeight = activeFontSize;
float dynScale = activeFontScale;
float labelHeight = fontHeight * dynScale;
float x = 0f, y = -padding.y;
int labelFontSize = (bitmapFont != null) ? bitmapFont.defaultSize : fontSize;
List<UILabel> labels = new List<UILabel>();
// Run through all items and create labels for each one
for (int i = 0, imax = items.Count; i < imax; ++i)
{
string s = items[i];
UILabel lbl = NGUITools.AddWidget<UILabel>(mChild);
lbl.pivot = UIWidget.Pivot.TopLeft;
lbl.bitmapFont = bitmapFont;
lbl.trueTypeFont = trueTypeFont;
lbl.fontSize = labelFontSize;
lbl.fontStyle = fontStyle;
lbl.text = isLocalized ? Localization.Get(s) : s;
lbl.color = textColor;
lbl.cachedTransform.localPosition = new Vector3(bgPadding.x + padding.x, y, -1f);
lbl.overflowMethod = UILabel.Overflow.ResizeFreely;
lbl.MakePixelPerfect();
if (dynScale != 1f) lbl.cachedTransform.localScale = Vector3.one * dynScale;
labels.Add(lbl);
y -= labelHeight;
y -= padding.y;
x = Mathf.Max(x, lbl.printedSize.x);
// Add an event listener
UIEventListener listener = UIEventListener.Get(lbl.gameObject);
listener.onHover = OnItemHover;
listener.onPress = OnItemPress;
listener.parameter = s;
// Move the selection here if this is the right label
if (mSelectedItem == s || (i == 0 && string.IsNullOrEmpty(mSelectedItem)))
Highlight(lbl, true);
// Add this label to the list
mLabelList.Add(lbl);
}
// The triggering widget's width should be the minimum allowed width
x = Mathf.Max(x, bounds.size.x * dynScale - (bgPadding.x + padding.x) * 2f);
float cx = x / dynScale;
Vector3 bcCenter = new Vector3(cx * 0.5f, -fontHeight * 0.5f, 0f);
Vector3 bcSize = new Vector3(cx, (labelHeight + padding.y) / dynScale, 1f);
// Run through all labels and add colliders
for (int i = 0, imax = labels.Count; i < imax; ++i)
{
UILabel lbl = labels[i];
BoxCollider bc = NGUITools.AddWidgetCollider(lbl.gameObject);
bcCenter.z = bc.center.z;
bc.center = bcCenter;
bc.size = bcSize;
}
x += (bgPadding.x + padding.x) * 2f;
y -= bgPadding.y;
// Scale the background sprite to envelop the entire set of items
mBackground.width = Mathf.RoundToInt(x);
mBackground.height = Mathf.RoundToInt(-y + bgPadding.y);
// Scale the highlight sprite to envelop a single item
float scaleFactor = 2f * atlas.pixelSize;
float w = x - (bgPadding.x + padding.x) * 2f + hlsp.borderLeft * scaleFactor;
float h = labelHeight + hlspHeight * scaleFactor;
mHighlight.width = Mathf.RoundToInt(w);
mHighlight.height = Mathf.RoundToInt(h);
bool placeAbove = (position == Position.Above);
if (position == Position.Auto)
{
UICamera cam = UICamera.FindCameraForLayer(gameObject.layer);
if (cam != null)
{
Vector3 viewPos = cam.cachedCamera.WorldToViewportPoint(myTrans.position);
placeAbove = (viewPos.y < 0.5f);
}
}
// If the list should be animated, let's animate it by expanding it
if (isAnimated)
{
float bottom = y + labelHeight;
Animate(mHighlight, placeAbove, bottom);
for (int i = 0, imax = labels.Count; i < imax; ++i) Animate(labels[i], placeAbove, bottom);
AnimateColor(mBackground);
AnimateScale(mBackground, placeAbove, bottom);
}
// If we need to place the popup list above the item, we need to reposition everything by the size of the list
if (placeAbove)
{
t.localPosition = new Vector3(bounds.min.x, bounds.max.y - y - bgPadding.y, bounds.min.z);
}
}
else OnSelect(false);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIPopupList.cs
|
C#
|
asf20
| 19,518
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Example script showing how to activate or deactivate a game object when a toggle's state changes.
/// OnActivate event is sent out by the UIToggle script.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Toggled Objects")]
public class UIToggledObjects : MonoBehaviour
{
public List<GameObject> activate;
public List<GameObject> deactivate;
[HideInInspector][SerializeField] GameObject target;
[HideInInspector][SerializeField] bool inverse = false;
void Awake ()
{
// Legacy functionality -- auto-upgrade
if (target != null)
{
if (activate.Count == 0 && deactivate.Count == 0)
{
if (inverse) deactivate.Add(target);
else activate.Add(target);
}
else target = null;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
UIToggle toggle = GetComponent<UIToggle>();
EventDelegate.Add(toggle.onChange, Toggle);
}
public void Toggle ()
{
bool val = UIToggle.current.value;
if (enabled)
{
for (int i = 0; i < activate.Count; ++i)
Set(activate[i], val);
for (int i = 0; i < deactivate.Count; ++i)
Set(deactivate[i], !val);
}
}
void Set (GameObject go, bool state)
{
if (go != null)
{
NGUITools.SetActive(go, state);
//UIPanel panel = NGUITools.FindInParents<UIPanel>(target);
//if (panel != null) panel.Refresh();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIToggledObjects.cs
|
C#
|
asf20
| 1,626
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// UIDragDropItem is a base script for your own Drag & Drop operations.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Drag and Drop Item")]
public class UIDragDropItem : MonoBehaviour
{
public enum Restriction
{
None,
Horizontal,
Vertical,
PressAndHold,
}
/// <summary>
/// What kind of restriction is applied to the drag & drop logic before dragging is made possible.
/// </summary>
public Restriction restriction = Restriction.None;
/// <summary>
/// Whether a copy of the item will be dragged instead of the item itself.
/// </summary>
public bool cloneOnDrag = false;
#region Common functionality
protected Transform mTrans;
protected Transform mParent;
protected Collider mCollider;
protected UIButton mButton;
protected UIRoot mRoot;
protected UIGrid mGrid;
protected UITable mTable;
protected int mTouchID = int.MinValue;
protected float mPressTime = 0f;
protected UIDragScrollView mDragScrollView = null;
/// <summary>
/// Cache the transform.
/// </summary>
protected virtual void Start ()
{
mTrans = transform;
mCollider = collider;
mButton = GetComponent<UIButton>();
mDragScrollView = GetComponent<UIDragScrollView>();
}
/// <summary>
/// Record the time the item was pressed on.
/// </summary>
void OnPress (bool isPressed) { if (isPressed) mPressTime = RealTime.time; }
/// <summary>
/// Start the dragging operation.
/// </summary>
void OnDragStart ()
{
if (!enabled || mTouchID != int.MinValue) return;
// If we have a restriction, check to see if its condition has been met first
if (restriction != Restriction.None)
{
if (restriction == Restriction.Horizontal)
{
Vector2 delta = UICamera.currentTouch.totalDelta;
if (Mathf.Abs(delta.x) < Mathf.Abs(delta.y)) return;
}
else if (restriction == Restriction.Vertical)
{
Vector2 delta = UICamera.currentTouch.totalDelta;
if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y)) return;
}
else if (restriction == Restriction.PressAndHold)
{
if (mPressTime + 1f > RealTime.time) return;
}
}
if (cloneOnDrag)
{
GameObject clone = NGUITools.AddChild(transform.parent.gameObject, gameObject);
clone.transform.localPosition = transform.localPosition;
clone.transform.localRotation = transform.localRotation;
clone.transform.localScale = transform.localScale;
UIButtonColor bc = clone.GetComponent<UIButtonColor>();
if (bc != null) bc.defaultColor = GetComponent<UIButtonColor>().defaultColor;
UICamera.currentTouch.dragged = clone;
UIDragDropItem item = clone.GetComponent<UIDragDropItem>();
item.Start();
item.OnDragDropStart();
}
else OnDragDropStart();
}
/// <summary>
/// Perform the dragging.
/// </summary>
void OnDrag (Vector2 delta)
{
if (!enabled || mTouchID != UICamera.currentTouchID) return;
OnDragDropMove((Vector3)delta * mRoot.pixelSizeAdjustment);
}
/// <summary>
/// Notification sent when the drag event has ended.
/// </summary>
void OnDragEnd ()
{
if (!enabled || mTouchID != UICamera.currentTouchID) return;
OnDragDropRelease(UICamera.hoveredObject);
}
#endregion
/// <summary>
/// Perform any logic related to starting the drag & drop operation.
/// </summary>
protected virtual void OnDragDropStart ()
{
// Automatically disable the scroll view
if (mDragScrollView != null) mDragScrollView.enabled = false;
// Disable the collider so that it doesn't intercept events
if (mButton != null) mButton.isEnabled = false;
else if (mCollider != null) mCollider.enabled = false;
mTouchID = UICamera.currentTouchID;
mParent = mTrans.parent;
mRoot = NGUITools.FindInParents<UIRoot>(mParent);
mGrid = NGUITools.FindInParents<UIGrid>(mParent);
mTable = NGUITools.FindInParents<UITable>(mParent);
// Re-parent the item
if (UIDragDropRoot.root != null)
mTrans.parent = UIDragDropRoot.root;
Vector3 pos = mTrans.localPosition;
pos.z = 0f;
mTrans.localPosition = pos;
TweenPosition tp = GetComponent<TweenPosition>();
if (tp != null) tp.enabled = false;
SpringPosition sp = GetComponent<SpringPosition>();
if (sp != null) sp.enabled = false;
// Notify the widgets that the parent has changed
NGUITools.MarkParentAsChanged(gameObject);
if (mTable != null) mTable.repositionNow = true;
if (mGrid != null) mGrid.repositionNow = true;
}
/// <summary>
/// Adjust the dragged object's position.
/// </summary>
protected virtual void OnDragDropMove (Vector3 delta)
{
mTrans.localPosition += delta;
}
/// <summary>
/// Drop the item onto the specified object.
/// </summary>
protected virtual void OnDragDropRelease (GameObject surface)
{
if (!cloneOnDrag)
{
mTouchID = int.MinValue;
// Re-enable the collider
if (mButton != null) mButton.isEnabled = true;
else if (mCollider != null) mCollider.enabled = true;
// Is there a droppable container?
UIDragDropContainer container = surface ? NGUITools.FindInParents<UIDragDropContainer>(surface) : null;
if (container != null)
{
// Container found -- parent this object to the container
mTrans.parent = (container.reparentTarget != null) ? container.reparentTarget : container.transform;
Vector3 pos = mTrans.localPosition;
pos.z = 0f;
mTrans.localPosition = pos;
}
else
{
// No valid container under the mouse -- revert the item's parent
mTrans.parent = mParent;
}
// Update the grid and table references
mParent = mTrans.parent;
mGrid = NGUITools.FindInParents<UIGrid>(mParent);
mTable = NGUITools.FindInParents<UITable>(mParent);
// Re-enable the drag scroll view script
if (mDragScrollView != null)
mDragScrollView.enabled = true;
// Notify the widgets that the parent has changed
NGUITools.MarkParentAsChanged(gameObject);
if (mTable != null) mTable.repositionNow = true;
if (mGrid != null) mGrid.repositionNow = true;
}
else NGUITools.Destroy(gameObject);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIDragDropItem.cs
|
C#
|
asf20
| 6,167
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Sample script showing how easy it is to implement a standard button that swaps sprites.
/// </summary>
[AddComponentMenu("NGUI/UI/Image Button")]
public class UIImageButton : MonoBehaviour
{
public UISprite target;
public string normalSprite;
public string hoverSprite;
public string pressedSprite;
public string disabledSprite;
public bool pixelSnap = true;
public bool isEnabled
{
get
{
Collider col = collider;
return col && col.enabled;
}
set
{
Collider col = collider;
if (!col) return;
if (col.enabled != value)
{
col.enabled = value;
UpdateImage();
}
}
}
void OnEnable ()
{
if (target == null) target = GetComponentInChildren<UISprite>();
UpdateImage();
}
void OnValidate ()
{
if (target != null)
{
if (string.IsNullOrEmpty(normalSprite)) normalSprite = target.spriteName;
if (string.IsNullOrEmpty(hoverSprite)) hoverSprite = target.spriteName;
if (string.IsNullOrEmpty(pressedSprite)) pressedSprite = target.spriteName;
if (string.IsNullOrEmpty(disabledSprite)) disabledSprite = target.spriteName;
}
}
void UpdateImage()
{
if (target != null)
{
if (isEnabled) SetSprite(UICamera.IsHighlighted(gameObject) ? hoverSprite : normalSprite);
else SetSprite(disabledSprite);
}
}
void OnHover (bool isOver)
{
if (isEnabled && target != null)
SetSprite(isOver ? hoverSprite : normalSprite);
}
void OnPress (bool pressed)
{
if (pressed) SetSprite(pressedSprite);
else UpdateImage();
}
void SetSprite (string sprite)
{
if (target.atlas == null || target.atlas.GetSprite(sprite) == null) return;
target.spriteName = sprite;
if (pixelSnap) target.MakePixelPerfect();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIImageButton.cs
|
C#
|
asf20
| 1,914
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Scroll bar functionality.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Interaction/NGUI Scroll Bar")]
public class UIScrollBar : UISlider
{
enum Direction
{
Horizontal,
Vertical,
Upgraded,
}
// Size of the scroll bar
[HideInInspector][SerializeField] protected float mSize = 1f;
// Deprecated functionality
[HideInInspector][SerializeField] float mScroll = 0f;
[HideInInspector][SerializeField] Direction mDir = Direction.Upgraded;
[System.Obsolete("Use 'value' instead")]
public float scrollValue { get { return this.value; } set { this.value = value; } }
/// <summary>
/// The size of the foreground bar in percent (0-1 range).
/// </summary>
public float barSize
{
get
{
return mSize;
}
set
{
float val = Mathf.Clamp01(value);
if (mSize != val)
{
mSize = val;
mIsDirty = true;
if (NGUITools.GetActive(this))
{
if (current == null && onChange != null)
{
current = this;
EventDelegate.Execute(onChange);
current = null;
}
ForceUpdate();
#if UNITY_EDITOR
if (!Application.isPlaying)
NGUITools.SetDirty(this);
#endif
}
}
}
}
/// <summary>
/// Upgrade from legacy functionality.
/// </summary>
protected override void Upgrade ()
{
if (mDir != Direction.Upgraded)
{
mValue = mScroll;
if (mDir == Direction.Horizontal)
{
mFill = mInverted ? FillDirection.RightToLeft : FillDirection.LeftToRight;
}
else
{
mFill = mInverted ? FillDirection.BottomToTop : FillDirection.TopToBottom;
}
mDir = Direction.Upgraded;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
}
/// <summary>
/// Make the scroll bar's foreground react to press events.
/// </summary>
protected override void OnStart ()
{
base.OnStart();
if (mFG != null && mFG.collider != null && mFG.gameObject != gameObject)
{
UIEventListener fgl = UIEventListener.Get(mFG.gameObject);
fgl.onPress += OnPressForeground;
fgl.onDrag += OnDragForeground;
mFG.autoResizeBoxCollider = true;
}
}
/// <summary>
/// Move the scroll bar to be centered on the specified position.
/// </summary>
protected override float LocalToValue (Vector2 localPos)
{
if (mFG != null)
{
float halfSize = Mathf.Clamp01(mSize) * 0.5f;
float val0 = halfSize;
float val1 = 1f - halfSize;
Vector3[] corners = mFG.localCorners;
if (isHorizontal)
{
val0 = Mathf.Lerp(corners[0].x, corners[2].x, val0);
val1 = Mathf.Lerp(corners[0].x, corners[2].x, val1);
float diff = (val1 - val0);
if (diff == 0f) return value;
return isInverted ?
(val1 - localPos.x) / diff :
(localPos.x - val0) / diff;
}
else
{
val0 = Mathf.Lerp(corners[0].y, corners[1].y, val0);
val1 = Mathf.Lerp(corners[3].y, corners[2].y, val1);
float diff = (val1 - val0);
if (diff == 0f) return value;
return isInverted ?
(val1 - localPos.y) / diff :
(localPos.y - val0) / diff;
}
}
return base.LocalToValue(localPos);
}
/// <summary>
/// Update the value of the scroll bar.
/// </summary>
public override void ForceUpdate ()
{
if (mFG != null)
{
mIsDirty = false;
float halfSize = Mathf.Clamp01(mSize) * 0.5f;
float pos = Mathf.Lerp(halfSize, 1f - halfSize, value);
float val0 = pos - halfSize;
float val1 = pos + halfSize;
if (isHorizontal)
{
mFG.drawRegion = isInverted ?
new Vector4(1f - val1, 0f, 1f - val0, 1f) :
new Vector4(val0, 0f, val1, 1f);
}
else
{
mFG.drawRegion = isInverted ?
new Vector4(0f, 1f - val1, 1f, 1f - val0) :
new Vector4(0f, val0, 1f, val1);
}
if (thumb != null)
{
Vector4 dr = mFG.drawingDimensions;
Vector3 v = new Vector3(
Mathf.Lerp(dr.x, dr.z, 0.5f),
Mathf.Lerp(dr.y, dr.w, 0.5f));
SetThumbPosition(mFG.cachedTransform.TransformPoint(v));
}
}
else base.ForceUpdate();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIScrollBar.cs
|
C#
|
asf20
| 4,177
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Attaching this script to an element of a scroll view will make it possible to center on it by clicking on it.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Center Scroll View on Click")]
public class UICenterOnClick : MonoBehaviour
{
void OnClick ()
{
UICenterOnChild center = NGUITools.FindInParents<UICenterOnChild>(gameObject);
UIPanel panel = NGUITools.FindInParents<UIPanel>(gameObject);
if (center != null)
{
if (center.enabled)
center.CenterOn(transform);
}
else if (panel != null && panel.clipping != UIDrawCall.Clipping.None)
{
UIScrollView sv = panel.GetComponent<UIScrollView>();
Vector3 offset = -panel.cachedTransform.InverseTransformPoint(transform.position);
if (!sv.canMoveHorizontally) offset.x = panel.cachedTransform.localPosition.x;
if (!sv.canMoveVertically) offset.y = panel.cachedTransform.localPosition.y;
SpringPanel.Begin(panel.cachedGameObject, offset, 6f);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UICenterOnClick.cs
|
C#
|
asf20
| 1,161
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Simple example script of how a button can be scaled visibly when the mouse hovers over it or it gets pressed.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Button Scale")]
public class UIButtonScale : MonoBehaviour
{
public Transform tweenTarget;
public Vector3 hover = new Vector3(1.1f, 1.1f, 1.1f);
public Vector3 pressed = new Vector3(1.05f, 1.05f, 1.05f);
public float duration = 0.2f;
Vector3 mScale;
bool mStarted = false;
void Start ()
{
if (!mStarted)
{
mStarted = true;
if (tweenTarget == null) tweenTarget = transform;
mScale = tweenTarget.localScale;
}
}
void OnEnable () { if (mStarted) OnHover(UICamera.IsHighlighted(gameObject)); }
void OnDisable ()
{
if (mStarted && tweenTarget != null)
{
TweenScale tc = tweenTarget.GetComponent<TweenScale>();
if (tc != null)
{
tc.value = mScale;
tc.enabled = false;
}
}
}
void OnPress (bool isPressed)
{
if (enabled)
{
if (!mStarted) Start();
TweenScale.Begin(tweenTarget.gameObject, duration, isPressed ? Vector3.Scale(mScale, pressed) :
(UICamera.IsHighlighted(gameObject) ? Vector3.Scale(mScale, hover) : mScale)).method = UITweener.Method.EaseInOut;
}
}
void OnHover (bool isOver)
{
if (enabled)
{
if (!mStarted) Start();
TweenScale.Begin(tweenTarget.gameObject, duration, isOver ? Vector3.Scale(mScale, hover) : mScale).method = UITweener.Method.EaseInOut;
}
}
void OnSelect (bool isSelected)
{
if (enabled && (!isSelected || UICamera.currentScheme == UICamera.ControlScheme.Controller))
OnHover(isSelected);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIButtonScale.cs
|
C#
|
asf20
| 1,802
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Simple example script of how a button can be rotated visibly when the mouse hovers over it or it gets pressed.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Button Rotation")]
public class UIButtonRotation : MonoBehaviour
{
public Transform tweenTarget;
public Vector3 hover = Vector3.zero;
public Vector3 pressed = Vector3.zero;
public float duration = 0.2f;
Quaternion mRot;
bool mStarted = false;
void Start ()
{
if (!mStarted)
{
mStarted = true;
if (tweenTarget == null) tweenTarget = transform;
mRot = tweenTarget.localRotation;
}
}
void OnEnable () { if (mStarted) OnHover(UICamera.IsHighlighted(gameObject)); }
void OnDisable ()
{
if (mStarted && tweenTarget != null)
{
TweenRotation tc = tweenTarget.GetComponent<TweenRotation>();
if (tc != null)
{
tc.value = mRot;
tc.enabled = false;
}
}
}
void OnPress (bool isPressed)
{
if (enabled)
{
if (!mStarted) Start();
TweenRotation.Begin(tweenTarget.gameObject, duration, isPressed ? mRot * Quaternion.Euler(pressed) :
(UICamera.IsHighlighted(gameObject) ? mRot * Quaternion.Euler(hover) : mRot)).method = UITweener.Method.EaseInOut;
}
}
void OnHover (bool isOver)
{
if (enabled)
{
if (!mStarted) Start();
TweenRotation.Begin(tweenTarget.gameObject, duration, isOver ? mRot * Quaternion.Euler(hover) :
mRot).method = UITweener.Method.EaseInOut;
}
}
void OnSelect (bool isSelected)
{
if (enabled && (!isSelected || UICamera.currentScheme == UICamera.ControlScheme.Controller))
OnHover(isSelected);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Interaction/UIButtonRotation.cs
|
C#
|
asf20
| 1,790
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections;
/// <summary>
/// Simple script that shows how to download a remote texture and assign it to be used by a UITexture.
/// </summary>
[RequireComponent(typeof(UITexture))]
public class DownloadTexture : MonoBehaviour
{
public string url = "http://www.yourwebsite.com/logo.png";
Texture2D mTex;
IEnumerator Start ()
{
WWW www = new WWW(url);
yield return www;
mTex = www.texture;
if (mTex != null)
{
UITexture ut = GetComponent<UITexture>();
ut.mainTexture = mTex;
ut.MakePixelPerfect();
}
www.Dispose();
}
void OnDestroy ()
{
if (mTex != null) Destroy(mTex);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/DownloadTexture.cs
|
C#
|
asf20
| 829
|
using UnityEngine;
/// <summary>
/// Change the shader level-of-detail to match the quality settings.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Examples/Shader Quality")]
public class ShaderQuality : MonoBehaviour
{
int mCurrent = 600;
void Update ()
{
int current = (QualitySettings.GetQualityLevel() + 1) * 100;
if (mCurrent != current)
{
mCurrent = current;
Shader.globalMaximumLOD = mCurrent;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/ShaderQuality.cs
|
C#
|
asf20
| 442
|
using UnityEngine;
public class OpenURLOnClick : MonoBehaviour
{
void OnClick ()
{
UILabel lbl = GetComponent<UILabel>();
if (lbl != null)
{
string url = lbl.GetUrlAtPosition(UICamera.lastHit.point);
if (!string.IsNullOrEmpty(url)) Application.OpenURL(url);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/OpenURLOnClick.cs
|
C#
|
asf20
| 285
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Trivial script that fills the label's contents gradually, as if someone was typing.
/// </summary>
[RequireComponent(typeof(UILabel))]
[AddComponentMenu("NGUI/Examples/Typewriter Effect")]
public class TypewriterEffect : MonoBehaviour
{
public int charsPerSecond = 40;
UILabel mLabel;
string mText;
int mOffset = 0;
float mNextChar = 0f;
bool mReset = true;
void OnEnable () { mReset = true; }
void Update ()
{
if (mReset)
{
mOffset = 0;
mReset = false;
mLabel = GetComponent<UILabel>();
mText = mLabel.processedText;
}
if (mOffset < mText.Length && mNextChar <= RealTime.time)
{
charsPerSecond = Mathf.Max(1, charsPerSecond);
// Periods and end-of-line characters should pause for a longer time.
float delay = 1f / charsPerSecond;
char c = mText[mOffset];
if (c == '.' || c == '\n' || c == '!' || c == '?') delay *= 4f;
// Automatically skip all symbols
NGUIText.ParseSymbol(mText, ref mOffset);
mNextChar = RealTime.time + delay;
mLabel.text = mText.Substring(0, ++mOffset);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/TypewriterEffect.cs
|
C#
|
asf20
| 1,274
|
using UnityEngine;
/// <summary>
/// Very simple example of how to use a TextList with a UIInput for chat.
/// </summary>
[RequireComponent(typeof(UIInput))]
[AddComponentMenu("NGUI/Examples/Chat Input")]
public class ChatInput : MonoBehaviour
{
public UITextList textList;
public bool fillWithDummyData = false;
UIInput mInput;
/// <summary>
/// Add some dummy text to the text list.
/// </summary>
void Start ()
{
mInput = GetComponent<UIInput>();
mInput.label.maxLineCount = 1;
if (fillWithDummyData && textList != null)
{
for (int i = 0; i < 30; ++i)
{
textList.Add(((i % 2 == 0) ? "[FFFFFF]" : "[AAAAAA]") +
"This is an example paragraph for the text list, testing line " + i + "[-]");
}
}
}
/// <summary>
/// Submit notification is sent by UIInput when 'enter' is pressed or iOS/Android keyboard finalizes input.
/// </summary>
public void OnSubmit ()
{
if (textList != null)
{
// It's a good idea to strip out all symbols as we don't want user input to alter colors, add new lines, etc
string text = NGUIText.StripSymbols(mInput.value);
if (!string.IsNullOrEmpty(text))
{
textList.Add(text);
mInput.value = "";
mInput.isSelected = false;
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/ChatInput.cs
|
C#
|
asf20
| 1,238
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
[AddComponentMenu("NGUI/Examples/Drag and Drop Item (Example)")]
public class ExampleDragDropItem : UIDragDropItem
{
/// <summary>
/// Prefab object that will be instantiated on the DragDropSurface if it receives the OnDrop event.
/// </summary>
public GameObject prefab;
/// <summary>
/// Drop a 3D game object onto the surface.
/// </summary>
protected override void OnDragDropRelease (GameObject surface)
{
if (surface != null)
{
ExampleDragDropSurface dds = surface.GetComponent<ExampleDragDropSurface>();
if (dds != null)
{
GameObject child = NGUITools.AddChild(dds.gameObject, prefab);
child.transform.localScale = dds.transform.localScale;
Transform trans = child.transform;
trans.position = UICamera.lastHit.point;
if (dds.rotatePlacedObject)
{
trans.rotation = Quaternion.LookRotation(UICamera.lastHit.normal) * Quaternion.Euler(90f, 0f, 0f);
}
// Destroy this icon as it's no longer needed
NGUITools.Destroy(gameObject);
return;
}
}
base.OnDragDropRelease(surface);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/ExampleDragDropItem.cs
|
C#
|
asf20
| 1,270
|
using UnityEngine;
/// <summary>
/// Attaching this script to an object will make it turn as it gets closer to left/right edges of the screen.
/// Look at how it's used in Example 6.
/// </summary>
[AddComponentMenu("NGUI/Examples/Window Auto-Yaw")]
public class WindowAutoYaw : MonoBehaviour
{
public int updateOrder = 0;
public Camera uiCamera;
public float yawAmount = 20f;
Transform mTrans;
void OnDisable ()
{
mTrans.localRotation = Quaternion.identity;
}
void OnEnable ()
{
if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
mTrans = transform;
}
void Update ()
{
if (uiCamera != null)
{
Vector3 pos = uiCamera.WorldToViewportPoint(mTrans.position);
mTrans.localRotation = Quaternion.Euler(0f, (pos.x * 2f - 1f) * yawAmount, 0f);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/WindowAutoYaw.cs
|
C#
|
asf20
| 809
|
using UnityEngine;
/// <summary>
/// Attach this script to a child of a draggable window to make it tilt as it's dragged.
/// Look at how it's used in Example 6.
/// </summary>
[AddComponentMenu("NGUI/Examples/Window Drag Tilt")]
public class WindowDragTilt : MonoBehaviour
{
public int updateOrder = 0;
public float degrees = 30f;
Vector3 mLastPos;
Transform mTrans;
float mAngle = 0f;
void OnEnable ()
{
mTrans = transform;
mLastPos = mTrans.position;
}
void Update ()
{
Vector3 deltaPos = mTrans.position - mLastPos;
mLastPos = mTrans.position;
mAngle += deltaPos.x * degrees;
mAngle = NGUIMath.SpringLerp(mAngle, 0f, 20f, Time.deltaTime);
mTrans.localRotation = Quaternion.Euler(0f, 0f, -mAngle);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/WindowDragTilt.cs
|
C#
|
asf20
| 737
|
using UnityEngine;
[AddComponentMenu("NGUI/Examples/Load Level On Click")]
public class LoadLevelOnClick : MonoBehaviour
{
public string levelName;
void OnClick ()
{
if (!string.IsNullOrEmpty(levelName))
{
Application.LoadLevel(levelName);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/LoadLevelOnClick.cs
|
C#
|
asf20
| 274
|
using UnityEngine;
/// <summary>
/// Want something to spin? Attach this script to it. Works equally well with rigidbodies as without.
/// </summary>
[AddComponentMenu("NGUI/Examples/Spin")]
public class Spin : MonoBehaviour
{
public Vector3 rotationsPerSecond = new Vector3(0f, 0.1f, 0f);
public bool ignoreTimeScale = false;
Rigidbody mRb;
Transform mTrans;
void Start ()
{
mTrans = transform;
mRb = rigidbody;
}
void Update ()
{
if (mRb == null)
{
ApplyDelta(ignoreTimeScale ? RealTime.deltaTime : Time.deltaTime);
}
}
void FixedUpdate ()
{
if (mRb != null)
{
ApplyDelta(Time.deltaTime);
}
}
public void ApplyDelta (float delta)
{
delta *= Mathf.Rad2Deg * Mathf.PI * 2f;
Quaternion offset = Quaternion.Euler(rotationsPerSecond * delta);
if (mRb == null)
{
mTrans.rotation = mTrans.rotation * offset;
}
else
{
mRb.MoveRotation(mRb.rotation * offset);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/Spin.cs
|
C#
|
asf20
| 927
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Example script that resizes the widget it's attached to in order to envelop the target content.
/// </summary>
[RequireComponent(typeof(UIWidget))]
[AddComponentMenu("NGUI/Examples/Envelop Content")]
public class EnvelopContent : MonoBehaviour
{
public Transform targetRoot;
public int padLeft = 0;
public int padRight = 0;
public int padBottom = 0;
public int padTop = 0;
void Start () { Execute(); }
[ContextMenu("Execute")]
public void Execute ()
{
if (targetRoot == transform)
{
Debug.LogError("Target Root object cannot be the same object that has Envelop Content. Make it a sibling instead.", this);
}
else if (NGUITools.IsChild(targetRoot, transform))
{
Debug.LogError("Target Root object should not be a parent of Envelop Content. Make it a sibling instead.", this);
}
else
{
Bounds b = NGUIMath.CalculateRelativeWidgetBounds(transform.parent, targetRoot, false);
float x0 = b.min.x + padLeft;
float y0 = b.min.y + padBottom;
float x1 = b.max.x + padRight;
float y1 = b.max.y + padTop;
UIWidget w = GetComponent<UIWidget>();
w.SetRect(x0, y0, x1 - x0, y1 - y0);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/EnvelopContent.cs
|
C#
|
asf20
| 1,357
|
using UnityEngine;
[AddComponentMenu("NGUI/Examples/Spin With Mouse")]
public class SpinWithMouse : MonoBehaviour
{
public Transform target;
public float speed = 1f;
Transform mTrans;
void Start ()
{
mTrans = transform;
}
void OnDrag (Vector2 delta)
{
UICamera.currentTouch.clickNotification = UICamera.ClickNotification.None;
if (target != null)
{
target.localRotation = Quaternion.Euler(0f, -0.5f * delta.x * speed, 0f) * target.localRotation;
}
else
{
mTrans.localRotation = Quaternion.Euler(0f, -0.5f * delta.x * speed, 0f) * mTrans.localRotation;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/SpinWithMouse.cs
|
C#
|
asf20
| 621
|
using UnityEngine;
/// <summary>
/// Simple script used by Tutorial 11 that sets the color of the sprite based on the string value.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(UIWidget))]
[AddComponentMenu("NGUI/Examples/Set Color on Selection")]
public class SetColorOnSelection : MonoBehaviour
{
UIWidget mWidget;
public void SetSpriteBySelection ()
{
if (UIPopupList.current == null) return;
if (mWidget == null) mWidget = GetComponent<UIWidget>();
switch (UIPopupList.current.value)
{
case "White": mWidget.color = Color.white; break;
case "Red": mWidget.color = Color.red; break;
case "Green": mWidget.color = Color.green; break;
case "Blue": mWidget.color = Color.blue; break;
case "Yellow": mWidget.color = Color.yellow; break;
case "Cyan": mWidget.color = Color.cyan; break;
case "Magenta": mWidget.color = Color.magenta; break;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/SetColorOnSelection.cs
|
C#
|
asf20
| 902
|
using UnityEngine;
/// <summary>
/// Attach to a game object to make its position always lag behind its parent as the parent moves.
/// </summary>
[AddComponentMenu("NGUI/Examples/Lag Position")]
public class LagPosition : MonoBehaviour
{
public int updateOrder = 0;
public Vector3 speed = new Vector3(10f, 10f, 10f);
public bool ignoreTimeScale = false;
Transform mTrans;
Vector3 mRelative;
Vector3 mAbsolute;
void OnEnable ()
{
mTrans = transform;
mAbsolute = mTrans.position;
mRelative = mTrans.localPosition;
}
void Update ()
{
Transform parent = mTrans.parent;
if (parent != null)
{
float delta = ignoreTimeScale ? RealTime.deltaTime : Time.deltaTime;
Vector3 target = parent.position + parent.rotation * mRelative;
mAbsolute.x = Mathf.Lerp(mAbsolute.x, target.x, Mathf.Clamp01(delta * speed.x));
mAbsolute.y = Mathf.Lerp(mAbsolute.y, target.y, Mathf.Clamp01(delta * speed.y));
mAbsolute.z = Mathf.Lerp(mAbsolute.z, target.z, Mathf.Clamp01(delta * speed.z));
mTrans.position = mAbsolute;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/LagPosition.cs
|
C#
|
asf20
| 1,052
|
using UnityEngine;
/// <summary>
/// Attach to a game object to make its rotation always lag behind its parent as the parent rotates.
/// </summary>
[AddComponentMenu("NGUI/Examples/Lag Rotation")]
public class LagRotation : MonoBehaviour
{
public int updateOrder = 0;
public float speed = 10f;
public bool ignoreTimeScale = false;
Transform mTrans;
Quaternion mRelative;
Quaternion mAbsolute;
void OnEnable()
{
mTrans = transform;
mRelative = mTrans.localRotation;
mAbsolute = mTrans.rotation;
}
void Update ()
{
Transform parent = mTrans.parent;
if (parent != null)
{
float delta = ignoreTimeScale ? RealTime.deltaTime : Time.deltaTime;
mAbsolute = Quaternion.Slerp(mAbsolute, parent.rotation * mRelative, delta * speed);
mTrans.rotation = mAbsolute;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/LagRotation.cs
|
C#
|
asf20
| 804
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// This script automatically changes the color of the specified sprite based on the value of the slider.
/// </summary>
[RequireComponent(typeof(UIProgressBar))]
[AddComponentMenu("NGUI/Examples/Slider Colors")]
public class UISliderColors : MonoBehaviour
{
public UISprite sprite;
public Color[] colors = new Color[] { Color.red, Color.yellow, Color.green };
UIProgressBar mBar;
void Start () { mBar = GetComponent<UIProgressBar>(); Update(); }
void Update ()
{
if (sprite == null || colors.Length == 0) return;
float val = mBar.value;
val *= (colors.Length - 1);
int startIndex = Mathf.FloorToInt(val);
Color c = colors[0];
if (startIndex >= 0)
{
if (startIndex + 1 < colors.Length)
{
float factor = (val - startIndex);
c = Color.Lerp(colors[startIndex], colors[startIndex + 1], factor);
}
else if (startIndex < colors.Length)
{
c = colors[startIndex];
}
else c = colors[colors.Length - 1];
}
c.a = sprite.color.a;
sprite.color = c;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/UISliderColors.cs
|
C#
|
asf20
| 1,230
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Simple example of an OnDrop event accepting a game object. In this case we check to see if there is a DragDropObject present,
/// and if so -- create its prefab on the surface, then destroy the object.
/// </summary>
[AddComponentMenu("NGUI/Examples/Drag and Drop Surface (Example)")]
public class ExampleDragDropSurface : MonoBehaviour
{
public bool rotatePlacedObject = false;
//void OnDrop (GameObject go)
//{
// ExampleDragDropItem ddo = go.GetComponent<ExampleDragDropItem>();
// if (ddo != null)
// {
// GameObject child = NGUITools.AddChild(gameObject, ddo.prefab);
// Transform trans = child.transform;
// trans.position = UICamera.lastHit.point;
// if (rotatePlacedObject) trans.rotation = Quaternion.LookRotation(UICamera.lastHit.normal) * Quaternion.Euler(90f, 0f, 0f);
// Destroy(go);
// }
//}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/ExampleDragDropSurface.cs
|
C#
|
asf20
| 1,094
|
using UnityEngine;
/// <summary>
/// Placing this script on the game object will make that game object pan with mouse movement.
/// </summary>
[AddComponentMenu("NGUI/Examples/Pan With Mouse")]
public class PanWithMouse : MonoBehaviour
{
public Vector2 degrees = new Vector2(5f, 3f);
public float range = 1f;
Transform mTrans;
Quaternion mStart;
Vector2 mRot = Vector2.zero;
void Start ()
{
mTrans = transform;
mStart = mTrans.localRotation;
}
void Update ()
{
float delta = RealTime.deltaTime;
Vector3 pos = Input.mousePosition;
float halfWidth = Screen.width * 0.5f;
float halfHeight = Screen.height * 0.5f;
if (range < 0.1f) range = 0.1f;
float x = Mathf.Clamp((pos.x - halfWidth) / halfWidth / range, -1f, 1f);
float y = Mathf.Clamp((pos.y - halfHeight) / halfHeight / range, -1f, 1f);
mRot = Vector2.Lerp(mRot, new Vector2(x, y), delta * 5f);
mTrans.localRotation = mStart * Quaternion.Euler(-mRot.y * degrees.y, mRot.x * degrees.x, 0f);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/PanWithMouse.cs
|
C#
|
asf20
| 990
|
using UnityEngine;
/// <summary>
/// This simple example script is used in Tutorial 5 to show how custom events work.
/// </summary>
public class Tutorial5 : MonoBehaviour
{
/// <summary>
/// This function is called by the duration slider. Since it's called by a slider,
/// UIProgressBar.current will contain the caller. It's identical to other NGUI components.
/// A button's callback will set UIButton.current, for example. Input field? UIInput.current, etc.
/// </summary>
public void SetDurationToCurrentProgress ()
{
UITweener[] tweens = GetComponentsInChildren<UITweener>();
foreach (UITweener tw in tweens)
{
// The slider's value is always limited in 0 to 1 range, however it's trivial to change it.
// For example, to make it range from 2.0 to 0.5 instead, you can do this:
tw.duration = Mathf.Lerp(2.0f, 0.5f, UIProgressBar.current.value);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/Tutorial5.cs
|
C#
|
asf20
| 888
|
using UnityEngine;
/// <summary>
/// Attaching this script to an object will make that object face the specified target.
/// The most ideal use for this script is to attach it to the camera and make the camera look at its target.
/// </summary>
[AddComponentMenu("NGUI/Examples/Look At Target")]
public class LookAtTarget : MonoBehaviour
{
public int level = 0;
public Transform target;
public float speed = 8f;
Transform mTrans;
void Start ()
{
mTrans = transform;
}
void LateUpdate ()
{
if (target != null)
{
Vector3 dir = target.position - mTrans.position;
float mag = dir.magnitude;
if (mag > 0.001f)
{
Quaternion lookRot = Quaternion.LookRotation(dir);
mTrans.rotation = Quaternion.Slerp(mTrans.rotation, lookRot, Mathf.Clamp01(speed * Time.deltaTime));
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/LookAtTarget.cs
|
C#
|
asf20
| 851
|
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Attach this script to any object that has idle animations.
/// It's expected that the main idle loop animation is called "idle", and idle
/// break animations all begin with "idle" (ex: idleStretch, idleYawn, etc).
/// The script will place the idle loop animation on layer 0, and breaks on layer 1.
/// </summary>
[AddComponentMenu("NGUI/Examples/Play Idle Animations")]
public class PlayIdleAnimations : MonoBehaviour
{
Animation mAnim;
AnimationClip mIdle;
List<AnimationClip> mBreaks = new List<AnimationClip>();
float mNextBreak = 0f;
int mLastIndex = 0;
/// <summary>
/// Find all idle animations.
/// </summary>
void Start ()
{
mAnim = GetComponentInChildren<Animation>();
if (mAnim == null)
{
Debug.LogWarning(NGUITools.GetHierarchy(gameObject) + " has no Animation component");
Destroy(this);
}
else
{
foreach (AnimationState state in mAnim)
{
if (state.clip.name == "idle")
{
state.layer = 0;
mIdle = state.clip;
mAnim.Play(mIdle.name);
}
else if (state.clip.name.StartsWith("idle"))
{
state.layer = 1;
mBreaks.Add(state.clip);
}
}
// No idle breaks found -- this script is unnecessary
if (mBreaks.Count == 0) Destroy(this);
}
}
/// <summary>
/// If it's time to play a new idle break animation, do so.
/// </summary>
void Update ()
{
if (mNextBreak < Time.time)
{
if (mBreaks.Count == 1)
{
// Only one break animation
AnimationClip clip = mBreaks[0];
mNextBreak = Time.time + clip.length + Random.Range(5f, 15f);
mAnim.CrossFade(clip.name);
}
else
{
int index = Random.Range(0, mBreaks.Count - 1);
// Never choose the same animation twice in a row
if (mLastIndex == index)
{
++index;
if (index >= mBreaks.Count) index = 0;
}
mLastIndex = index;
AnimationClip clip = mBreaks[index];
mNextBreak = Time.time + clip.length + Random.Range(2f, 8f);
mAnim.CrossFade(clip.name);
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/Other/PlayIdleAnimations.cs
|
C#
|
asf20
| 2,152
|
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Inventory System search functionality.
/// </summary>
public class InvFindItem : ScriptableWizard
{
/// <summary>
/// Private class used to return data from the Find function below.
/// </summary>
struct FindResult
{
public InvDatabase db;
public InvBaseItem item;
}
string mItemName = "";
List<FindResult> mResults = new List<FindResult>();
/// <summary>
/// Add a menu option to display this wizard.
/// </summary>
[MenuItem("Window/Find Item #&i")]
static void FindItem ()
{
ScriptableWizard.DisplayWizard<InvFindItem>("Find Item");
}
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
string newItemName = EditorGUILayout.TextField("Search for:", mItemName);
NGUIEditorTools.DrawSeparator();
if (GUI.changed || newItemName != mItemName)
{
mItemName = newItemName;
if (string.IsNullOrEmpty(mItemName))
{
mResults.Clear();
}
else
{
FindAllByName(mItemName);
}
}
if (mResults.Count == 0)
{
if (!string.IsNullOrEmpty(mItemName))
{
GUILayout.Label("No matches found");
}
}
else
{
Print3("Item ID", "Item Name", "Path", false);
NGUIEditorTools.DrawSeparator();
foreach (FindResult fr in mResults)
{
if (Print3(InvDatabase.FindItemID(fr.item).ToString(),
fr.item.name, NGUITools.GetHierarchy(fr.db.gameObject), true))
{
InvDatabaseInspector.SelectIndex(fr.db, fr.item);
Selection.activeGameObject = fr.db.gameObject;
EditorUtility.SetDirty(Selection.activeGameObject);
}
}
}
}
/// <summary>
/// Helper function used to print things in columns.
/// </summary>
bool Print3 (string a, string b, string c, bool button)
{
bool retVal = false;
GUILayout.BeginHorizontal();
{
GUILayout.Label(a, GUILayout.Width(80f));
GUILayout.Label(b, GUILayout.Width(160f));
GUILayout.Label(c);
if (button)
{
retVal = GUILayout.Button("Select", GUILayout.Width(60f));
}
else
{
GUILayout.Space(60f);
}
}
GUILayout.EndHorizontal();
return retVal;
}
/// <summary>
/// Find items by name.
/// </summary>
void FindAllByName (string partial)
{
partial = partial.ToLower();
mResults.Clear();
// Exact match comes first
foreach (InvDatabase db in InvDatabase.list)
{
foreach (InvBaseItem item in db.items)
{
if (item.name.Equals(partial, System.StringComparison.OrdinalIgnoreCase))
{
FindResult fr = new FindResult();
fr.db = db;
fr.item = item;
mResults.Add(fr);
}
}
}
// Next come partial matches that begin with the specified string
foreach (InvDatabase db in InvDatabase.list)
{
foreach (InvBaseItem item in db.items)
{
if (item.name.StartsWith(partial, System.StringComparison.OrdinalIgnoreCase))
{
bool exists = false;
foreach (FindResult res in mResults)
{
if (res.item == item)
{
exists = true;
break;
}
}
if (!exists)
{
FindResult fr = new FindResult();
fr.db = db;
fr.item = item;
mResults.Add(fr);
}
}
}
}
// Other partial matches come last
foreach (InvDatabase db in InvDatabase.list)
{
foreach (InvBaseItem item in db.items)
{
if (item.name.ToLower().Contains(partial))
{
bool exists = false;
foreach (FindResult res in mResults)
{
if (res.item == item)
{
exists = true;
break;
}
}
if (!exists)
{
FindResult fr = new FindResult();
fr.db = db;
fr.item = item;
mResults.Add(fr);
}
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/Editor/InvFindItem.cs
|
C#
|
asf20
| 3,735
|
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to edit Inventory Databases.
/// </summary>
[CustomEditor(typeof(InvDatabase))]
public class InvDatabaseInspector : Editor
{
static int mIndex = 0;
bool mConfirmDelete = false;
/// <summary>
/// Draw an enlarged sprite within the specified texture atlas.
/// </summary>
public Rect DrawSprite (Texture2D tex, Rect sprite, Material mat) { return DrawSprite(tex, sprite, mat, true, 0); }
/// <summary>
/// Draw an enlarged sprite within the specified texture atlas.
/// </summary>
public Rect DrawSprite (Texture2D tex, Rect sprite, Material mat, bool addPadding)
{
return DrawSprite(tex, sprite, mat, addPadding, 0);
}
/// <summary>
/// Draw an enlarged sprite within the specified texture atlas.
/// </summary>
public Rect DrawSprite (Texture2D tex, Rect sprite, Material mat, bool addPadding, int maxSize)
{
float paddingX = addPadding ? 4f / tex.width : 0f;
float paddingY = addPadding ? 4f / tex.height : 0f;
float ratio = (sprite.height + paddingY) / (sprite.width + paddingX);
ratio *= (float)tex.height / tex.width;
// Draw the checkered background
Color c = GUI.color;
Rect rect = NGUIEditorTools.DrawBackground(tex, ratio);
GUI.color = c;
if (maxSize > 0)
{
float dim = maxSize / Mathf.Max(rect.width, rect.height);
rect.width *= dim;
rect.height *= dim;
}
// We only want to draw into this rectangle
if (Event.current.type == EventType.Repaint)
{
if (mat == null)
{
GUI.DrawTextureWithTexCoords(rect, tex, sprite);
}
else
{
// NOTE: DrawPreviewTexture doesn't seem to support BeginGroup-based clipping
// when a custom material is specified. It seems to be a bug in Unity.
// Passing 'null' for the material or omitting the parameter clips as expected.
UnityEditor.EditorGUI.DrawPreviewTexture(sprite, tex, mat);
//UnityEditor.EditorGUI.DrawPreviewTexture(drawRect, tex);
//GUI.DrawTexture(drawRect, tex);
}
rect = new Rect(sprite.x + rect.x, sprite.y + rect.y, sprite.width, sprite.height);
}
return rect;
}
/// <summary>
/// Helper function that sets the index to the index of the specified item.
/// </summary>
public static void SelectIndex (InvDatabase db, InvBaseItem item)
{
mIndex = 0;
foreach (InvBaseItem i in db.items)
{
if (i == item) break;
++mIndex;
}
}
/// <summary>
/// Draw the inspector widget.
/// </summary>
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
InvDatabase db = target as InvDatabase;
NGUIEditorTools.DrawSeparator();
InvBaseItem item = null;
if (db.items == null || db.items.Count == 0)
{
mIndex = 0;
}
else
{
mIndex = Mathf.Clamp(mIndex, 0, db.items.Count - 1);
item = db.items[mIndex];
}
if (mConfirmDelete)
{
// Show the confirmation dialog
GUILayout.Label("Are you sure you want to delete '" + item.name + "'?");
NGUIEditorTools.DrawSeparator();
GUILayout.BeginHorizontal();
{
GUI.backgroundColor = Color.green;
if (GUILayout.Button("Cancel")) mConfirmDelete = false;
GUI.backgroundColor = Color.red;
if (GUILayout.Button("Delete"))
{
NGUIEditorTools.RegisterUndo("Delete Inventory Item", db);
db.items.RemoveAt(mIndex);
mConfirmDelete = false;
}
GUI.backgroundColor = Color.white;
}
GUILayout.EndHorizontal();
}
else
{
// Database icon atlas
UIAtlas atlas = EditorGUILayout.ObjectField("Icon Atlas", db.iconAtlas, typeof(UIAtlas), false) as UIAtlas;
if (atlas != db.iconAtlas)
{
NGUIEditorTools.RegisterUndo("Databse Atlas change", db);
db.iconAtlas = atlas;
foreach (InvBaseItem i in db.items) i.iconAtlas = atlas;
}
// Database ID
int dbID = EditorGUILayout.IntField("Database ID", db.databaseID);
if (dbID != db.databaseID)
{
NGUIEditorTools.RegisterUndo("Database ID change", db);
db.databaseID = dbID;
}
// "New" button
GUI.backgroundColor = Color.green;
if (GUILayout.Button("New Item"))
{
NGUIEditorTools.RegisterUndo("Add Inventory Item", db);
InvBaseItem bi = new InvBaseItem();
bi.iconAtlas = db.iconAtlas;
bi.id16 = (db.items.Count > 0) ? db.items[db.items.Count - 1].id16 + 1 : 0;
db.items.Add(bi);
mIndex = db.items.Count - 1;
if (item != null)
{
bi.name = "Copy of " + item.name;
bi.description = item.description;
bi.slot = item.slot;
bi.color = item.color;
bi.iconName = item.iconName;
bi.attachment = item.attachment;
bi.minItemLevel = item.minItemLevel;
bi.maxItemLevel = item.maxItemLevel;
foreach (InvStat stat in item.stats)
{
InvStat copy = new InvStat();
copy.id = stat.id;
copy.amount = stat.amount;
copy.modifier = stat.modifier;
bi.stats.Add(copy);
}
}
else
{
bi.name = "New Item";
bi.description = "Item Description";
}
item = bi;
}
GUI.backgroundColor = Color.white;
if (item != null)
{
NGUIEditorTools.DrawSeparator();
// Navigation section
GUILayout.BeginHorizontal();
{
if (mIndex == 0) GUI.color = Color.grey;
if (GUILayout.Button("<<")) { mConfirmDelete = false; --mIndex; }
GUI.color = Color.white;
mIndex = EditorGUILayout.IntField(mIndex + 1, GUILayout.Width(40f)) - 1;
GUILayout.Label("/ " + db.items.Count, GUILayout.Width(40f));
if (mIndex + 1 == db.items.Count) GUI.color = Color.grey;
if (GUILayout.Button(">>")) { mConfirmDelete = false; ++mIndex; }
GUI.color = Color.white;
}
GUILayout.EndHorizontal();
NGUIEditorTools.DrawSeparator();
// Item name and delete item button
GUILayout.BeginHorizontal();
{
string itemName = EditorGUILayout.TextField("Item Name", item.name);
GUI.backgroundColor = Color.red;
if (GUILayout.Button("Delete", GUILayout.Width(55f)))
{
mConfirmDelete = true;
}
GUI.backgroundColor = Color.white;
if (!itemName.Equals(item.name))
{
NGUIEditorTools.RegisterUndo("Rename Item", db);
item.name = itemName;
}
}
GUILayout.EndHorizontal();
string itemDesc = GUILayout.TextArea(item.description, 200, GUILayout.Height(100f));
InvBaseItem.Slot slot = (InvBaseItem.Slot)EditorGUILayout.EnumPopup("Slot", item.slot);
string iconName = "";
float iconSize = 64f;
bool drawIcon = false;
float extraSpace = 0f;
if (item.iconAtlas != null)
{
BetterList<string> sprites = item.iconAtlas.GetListOfSprites();
sprites.Insert(0, "<None>");
int index = 0;
string spriteName = (item.iconName != null) ? item.iconName : sprites[0];
// We need to find the sprite in order to have it selected
if (!string.IsNullOrEmpty(spriteName))
{
for (int i = 1; i < sprites.size; ++i)
{
if (spriteName.Equals(sprites[i], System.StringComparison.OrdinalIgnoreCase))
{
index = i;
break;
}
}
}
// Draw the sprite selection popup
index = EditorGUILayout.Popup("Icon", index, sprites.ToArray());
UISpriteData sprite = (index > 0) ? item.iconAtlas.GetSprite(sprites[index]) : null;
if (sprite != null)
{
iconName = sprite.name;
Material mat = item.iconAtlas.spriteMaterial;
if (mat != null)
{
Texture2D tex = mat.mainTexture as Texture2D;
if (tex != null)
{
drawIcon = true;
Rect rect = new Rect(sprite.x, sprite.y, sprite.width, sprite.height);
rect = NGUIMath.ConvertToTexCoords(rect, tex.width, tex.height);
GUILayout.Space(4f);
GUILayout.BeginHorizontal();
{
GUILayout.Space(Screen.width - iconSize);
DrawSprite(tex, rect, null, false);
}
GUILayout.EndHorizontal();
extraSpace = iconSize * (float)sprite.height / sprite.width;
}
}
}
}
// Item level range
GUILayout.BeginHorizontal();
GUILayout.Label("Level Range", GUILayout.Width(77f));
int min = EditorGUILayout.IntField(item.minItemLevel, GUILayout.MinWidth(40f));
int max = EditorGUILayout.IntField(item.maxItemLevel, GUILayout.MinWidth(40f));
if (drawIcon) GUILayout.Space(iconSize);
GUILayout.EndHorizontal();
// Game Object attachment field, left of the icon
GUILayout.BeginHorizontal();
GameObject go = (GameObject)EditorGUILayout.ObjectField("Attachment", item.attachment, typeof(GameObject), false);
if (drawIcon) GUILayout.Space(iconSize);
GUILayout.EndHorizontal();
// Color tint field, left of the icon
GUILayout.BeginHorizontal();
Color color = EditorGUILayout.ColorField("Color", item.color);
if (drawIcon) GUILayout.Space(iconSize);
GUILayout.EndHorizontal();
// Calculate the extra spacing necessary for the icon to show up properly and not overlap anything
if (drawIcon)
{
extraSpace = Mathf.Max(0f, extraSpace - 60f);
GUILayout.Space(extraSpace);
}
// Item stats
NGUIEditorTools.DrawSeparator();
if (item.stats != null)
{
for (int i = 0; i < item.stats.Count; ++i)
{
InvStat stat = item.stats[i];
GUILayout.BeginHorizontal();
{
InvStat.Identifier iden = (InvStat.Identifier)EditorGUILayout.EnumPopup(stat.id, GUILayout.Width(80f));
// Color the field red if it's negative, green if it's positive
if (stat.amount > 0) GUI.backgroundColor = Color.green;
else if (stat.amount < 0) GUI.backgroundColor = Color.red;
int amount = EditorGUILayout.IntField(stat.amount, GUILayout.Width(40f));
GUI.backgroundColor = Color.white;
InvStat.Modifier mod = (InvStat.Modifier)EditorGUILayout.EnumPopup(stat.modifier);
GUI.backgroundColor = Color.red;
if (GUILayout.Button("X", GUILayout.Width(20f)))
{
NGUIEditorTools.RegisterUndo("Delete Item Stat", db);
item.stats.RemoveAt(i);
--i;
}
else if (iden != stat.id || amount != stat.amount || mod != stat.modifier)
{
NGUIEditorTools.RegisterUndo("Item Stats", db);
stat.id = iden;
stat.amount = amount;
stat.modifier = mod;
}
GUI.backgroundColor = Color.white;
}
GUILayout.EndHorizontal();
}
}
if (GUILayout.Button("Add Stat", GUILayout.Width(80f)))
{
NGUIEditorTools.RegisterUndo("Add Item Stat", db);
InvStat stat = new InvStat();
stat.id = InvStat.Identifier.Armor;
item.stats.Add(stat);
}
// Save all values
if (!itemDesc.Equals(item.description) ||
slot != item.slot ||
go != item.attachment ||
color != item.color ||
min != item.minItemLevel ||
max != item.maxItemLevel ||
!iconName.Equals(item.iconName))
{
NGUIEditorTools.RegisterUndo("Item Properties", db);
item.description = itemDesc;
item.slot = slot;
item.attachment = go;
item.color = color;
item.iconName = iconName;
item.minItemLevel = min;
item.maxItemLevel = max;
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/Editor/InvDatabaseInspector.cs
|
C#
|
asf20
| 11,185
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Equip the specified items on the character when the script is started.
/// </summary>
[AddComponentMenu("NGUI/Examples/Equip Items")]
public class EquipItems : MonoBehaviour
{
public int[] itemIDs;
void Start ()
{
if (itemIDs != null && itemIDs.Length > 0)
{
InvEquipment eq = GetComponent<InvEquipment>();
if (eq == null) eq = gameObject.AddComponent<InvEquipment>();
int qualityLevels = (int)InvGameItem.Quality._LastDoNotUse;
for (int i = 0, imax = itemIDs.Length; i < imax; ++i)
{
int index = itemIDs[i];
InvBaseItem item = InvDatabase.FindByID(index);
if (item != null)
{
InvGameItem gi = new InvGameItem(index, item);
gi.quality = (InvGameItem.Quality)Random.Range(0, qualityLevels);
gi.itemLevel = NGUITools.RandomRange(item.minItemLevel, item.maxItemLevel);
eq.Equip(gi);
}
else
{
Debug.LogWarning("Can't resolve the item ID of " + index);
}
}
}
Destroy(this);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/Game/EquipItems.cs
|
C#
|
asf20
| 1,234
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Abstract UI component observing an item somewhere in the inventory. This item can be equipped on
/// the character, it can be lying in a chest, or it can be hot-linked by another player. Either way,
/// all the common behavior is in this class. What the observed item actually is...
/// that's up to the derived class to determine.
/// </summary>
public abstract class UIItemSlot : MonoBehaviour
{
public UISprite icon;
public UIWidget background;
public UILabel label;
public AudioClip grabSound;
public AudioClip placeSound;
public AudioClip errorSound;
InvGameItem mItem;
string mText = "";
static InvGameItem mDraggedItem;
/// <summary>
/// This function should return the item observed by this UI class.
/// </summary>
abstract protected InvGameItem observedItem { get; }
/// <summary>
/// Replace the observed item with the specified value. Should return the item that was replaced.
/// </summary>
abstract protected InvGameItem Replace (InvGameItem item);
/// <summary>
/// Show a tooltip for the item.
/// </summary>
void OnTooltip (bool show)
{
InvGameItem item = show ? mItem : null;
if (item != null)
{
InvBaseItem bi = item.baseItem;
if (bi != null)
{
string t = "[" + NGUIText.EncodeColor(item.color) + "]" + item.name + "[-]\n";
t += "[AFAFAF]Level " + item.itemLevel + " " + bi.slot;
List<InvStat> stats = item.CalculateStats();
for (int i = 0, imax = stats.Count; i < imax; ++i)
{
InvStat stat = stats[i];
if (stat.amount == 0) continue;
if (stat.amount < 0)
{
t += "\n[FF0000]" + stat.amount;
}
else
{
t += "\n[00FF00]+" + stat.amount;
}
if (stat.modifier == InvStat.Modifier.Percent) t += "%";
t += " " + stat.id;
t += "[-]";
}
if (!string.IsNullOrEmpty(bi.description)) t += "\n[FF9900]" + bi.description;
UITooltip.ShowText(t);
return;
}
}
UITooltip.ShowText(null);
}
/// <summary>
/// Allow to move objects around via drag & drop.
/// </summary>
void OnClick ()
{
if (mDraggedItem != null)
{
OnDrop(null);
}
else if (mItem != null)
{
mDraggedItem = Replace(null);
if (mDraggedItem != null) NGUITools.PlaySound(grabSound);
UpdateCursor();
}
}
/// <summary>
/// Start dragging the item.
/// </summary>
void OnDrag (Vector2 delta)
{
if (mDraggedItem == null && mItem != null)
{
UICamera.currentTouch.clickNotification = UICamera.ClickNotification.BasedOnDelta;
mDraggedItem = Replace(null);
NGUITools.PlaySound(grabSound);
UpdateCursor();
}
}
/// <summary>
/// Stop dragging the item.
/// </summary>
void OnDrop (GameObject go)
{
InvGameItem item = Replace(mDraggedItem);
if (mDraggedItem == item) NGUITools.PlaySound(errorSound);
else if (item != null) NGUITools.PlaySound(grabSound);
else NGUITools.PlaySound(placeSound);
mDraggedItem = item;
UpdateCursor();
}
/// <summary>
/// Set the cursor to the icon of the item being dragged.
/// </summary>
void UpdateCursor ()
{
if (mDraggedItem != null && mDraggedItem.baseItem != null)
{
UICursor.Set(mDraggedItem.baseItem.iconAtlas, mDraggedItem.baseItem.iconName);
}
else
{
UICursor.Clear();
}
}
/// <summary>
/// Keep an eye on the item and update the icon when it changes.
/// </summary>
void Update ()
{
InvGameItem i = observedItem;
if (mItem != i)
{
mItem = i;
InvBaseItem baseItem = (i != null) ? i.baseItem : null;
if (label != null)
{
string itemName = (i != null) ? i.name : null;
if (string.IsNullOrEmpty(mText)) mText = label.text;
label.text = (itemName != null) ? itemName : mText;
}
if (icon != null)
{
if (baseItem == null || baseItem.iconAtlas == null)
{
icon.enabled = false;
}
else
{
icon.atlas = baseItem.iconAtlas;
icon.spriteName = baseItem.iconName;
icon.enabled = true;
icon.MakePixelPerfect();
}
}
if (background != null)
{
background.color = (i != null) ? i.color : Color.white;
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/Game/UIItemSlot.cs
|
C#
|
asf20
| 4,328
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// A UI script that keeps an eye on the slot in a storage container.
/// </summary>
[AddComponentMenu("NGUI/Examples/UI Storage Slot")]
public class UIStorageSlot : UIItemSlot
{
public UIItemStorage storage;
public int slot = 0;
override protected InvGameItem observedItem
{
get
{
return (storage != null) ? storage.GetItem(slot) : null;
}
}
/// <summary>
/// Replace the observed item with the specified value. Should return the item that was replaced.
/// </summary>
override protected InvGameItem Replace (InvGameItem item)
{
return (storage != null) ? storage.Replace(slot, item) : item;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/Game/UIStorageSlot.cs
|
C#
|
asf20
| 876
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Create and equip a random item on the specified target.
/// </summary>
[AddComponentMenu("NGUI/Examples/Equip Random Item")]
public class EquipRandomItem : MonoBehaviour
{
public InvEquipment equipment;
void OnClick()
{
if (equipment == null) return;
List<InvBaseItem> list = InvDatabase.list[0].items;
if (list.Count == 0) return;
int qualityLevels = (int)InvGameItem.Quality._LastDoNotUse;
int index = Random.Range(0, list.Count);
InvBaseItem item = list[index];
InvGameItem gi = new InvGameItem(index, item);
gi.quality = (InvGameItem.Quality)Random.Range(0, qualityLevels);
gi.itemLevel = NGUITools.RandomRange(item.minItemLevel, item.maxItemLevel);
equipment.Equip(gi);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/Game/EquipRandomItem.cs
|
C#
|
asf20
| 997
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Storage container that stores items.
/// </summary>
[AddComponentMenu("NGUI/Examples/UI Item Storage")]
public class UIItemStorage : MonoBehaviour
{
/// <summary>
/// Maximum size of the container. Adding more items than this number will not work.
/// </summary>
public int maxItemCount = 8;
/// <summary>
/// Maximum number of rows to create.
/// </summary>
public int maxRows = 4;
/// <summary>
/// Maximum number of columns to create.
/// </summary>
public int maxColumns = 4;
/// <summary>
/// Template used to create inventory icons.
/// </summary>
public GameObject template;
/// <summary>
/// Background widget to scale after the item slots have been created.
/// </summary>
public UIWidget background;
/// <summary>
/// Spacing between icons.
/// </summary>
public int spacing = 128;
/// <summary>
/// Padding around the border.
/// </summary>
public int padding = 10;
List<InvGameItem> mItems = new List<InvGameItem>();
/// <summary>
/// List of items in the container.
/// </summary>
public List<InvGameItem> items { get { while (mItems.Count < maxItemCount) mItems.Add(null); return mItems; } }
/// <summary>
/// Convenience function that returns an item at the specified slot.
/// </summary>
public InvGameItem GetItem (int slot) { return (slot < items.Count) ? mItems[slot] : null; }
/// <summary>
/// Replace an item in the container with the specified one.
/// </summary>
/// <returns>An item that was replaced.</returns>
public InvGameItem Replace (int slot, InvGameItem item)
{
if (slot < maxItemCount)
{
InvGameItem prev = items[slot];
mItems[slot] = item;
return prev;
}
return item;
}
/// <summary>
/// Initialize the container and create an appropriate number of UI slots.
/// </summary>
void Start ()
{
if (template != null)
{
int count = 0;
Bounds b = new Bounds();
for (int y = 0; y < maxRows; ++y)
{
for (int x = 0; x < maxColumns; ++x)
{
GameObject go = NGUITools.AddChild(gameObject, template);
Transform t = go.transform;
t.localPosition = new Vector3(padding + (x + 0.5f) * spacing, -padding - (y + 0.5f) * spacing, 0f);
UIStorageSlot slot = go.GetComponent<UIStorageSlot>();
if (slot != null)
{
slot.storage = this;
slot.slot = count;
}
b.Encapsulate(new Vector3(padding * 2f + (x + 1) * spacing, -padding * 2f - (y + 1) * spacing, 0f));
if (++count >= maxItemCount)
{
if (background != null)
{
background.transform.localScale = b.size;
}
return;
}
}
}
if (background != null) background.transform.localScale = b.size;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/Game/UIItemStorage.cs
|
C#
|
asf20
| 3,076
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// A UI script that keeps an eye on the slot in character equipment.
/// </summary>
[AddComponentMenu("NGUI/Examples/UI Equipment Slot")]
public class UIEquipmentSlot : UIItemSlot
{
public InvEquipment equipment;
public InvBaseItem.Slot slot;
override protected InvGameItem observedItem
{
get
{
return (equipment != null) ? equipment.GetItem(slot) : null;
}
}
/// <summary>
/// Replace the observed item with the specified value. Should return the item that was replaced.
/// </summary>
override protected InvGameItem Replace (InvGameItem item)
{
return (equipment != null) ? equipment.Replace(slot, item) : item;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/Game/UIEquipmentSlot.cs
|
C#
|
asf20
| 898
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Selectable sprite that follows the mouse.
/// </summary>
[RequireComponent(typeof(UISprite))]
[AddComponentMenu("NGUI/Examples/UI Cursor")]
public class UICursor : MonoBehaviour
{
static public UICursor instance;
// Camera used to draw this cursor
public Camera uiCamera;
Transform mTrans;
UISprite mSprite;
UIAtlas mAtlas;
string mSpriteName;
/// <summary>
/// Keep an instance reference so this class can be easily found.
/// </summary>
void Awake () { instance = this; }
void OnDestroy () { instance = null; }
/// <summary>
/// Cache the expected components and starting values.
/// </summary>
void Start ()
{
mTrans = transform;
mSprite = GetComponentInChildren<UISprite>();
if (uiCamera == null)
uiCamera = NGUITools.FindCameraForLayer(gameObject.layer);
if (mSprite != null)
{
mAtlas = mSprite.atlas;
mSpriteName = mSprite.spriteName;
if (mSprite.depth < 100) mSprite.depth = 100;
}
}
/// <summary>
/// Reposition the widget.
/// </summary>
void Update ()
{
Vector3 pos = Input.mousePosition;
if (uiCamera != null)
{
// Since the screen can be of different than expected size, we want to convert
// mouse coordinates to view space, then convert that to world position.
pos.x = Mathf.Clamp01(pos.x / Screen.width);
pos.y = Mathf.Clamp01(pos.y / Screen.height);
mTrans.position = uiCamera.ViewportToWorldPoint(pos);
// For pixel-perfect results
if (uiCamera.isOrthoGraphic)
{
Vector3 lp = mTrans.localPosition;
lp.x = Mathf.Round(lp.x);
lp.y = Mathf.Round(lp.y);
mTrans.localPosition = lp;
}
}
else
{
// Simple calculation that assumes that the camera is of fixed size
pos.x -= Screen.width * 0.5f;
pos.y -= Screen.height * 0.5f;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
mTrans.localPosition = pos;
}
}
/// <summary>
/// Clear the cursor back to its original value.
/// </summary>
static public void Clear ()
{
if (instance != null && instance.mSprite != null)
Set(instance.mAtlas, instance.mSpriteName);
}
/// <summary>
/// Override the cursor with the specified sprite.
/// </summary>
static public void Set (UIAtlas atlas, string sprite)
{
if (instance != null && instance.mSprite)
{
instance.mSprite.atlas = atlas;
instance.mSprite.spriteName = sprite;
instance.mSprite.MakePixelPerfect();
instance.Update();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/Game/UICursor.cs
|
C#
|
asf20
| 2,640
|
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Inventory System statistic
/// </summary>
[System.Serializable]
public class InvStat
{
/// <summary>
/// Customize this enum with statistics appropriate for your own game
/// </summary>
public enum Identifier
{
Strength,
Constitution,
Agility,
Intelligence,
Damage,
Crit,
Armor,
Health,
Mana,
Other,
}
/// <summary>
/// Formula for final stats: [sum of raw amounts] * (1 + [sum of percent amounts])
/// </summary>
public enum Modifier
{
Added,
Percent,
}
public Identifier id;
public Modifier modifier;
public int amount;
/// <summary>
/// Get the localized name of the stat.
/// </summary>
static public string GetName (Identifier i)
{
return i.ToString();
}
/// <summary>
/// Get the localized stat's description -- adjust this to fit your own stats.
/// </summary>
static public string GetDescription (Identifier i)
{
switch (i)
{
case Identifier.Strength: return "Strength increases melee damage";
case Identifier.Constitution: return "Constitution increases health";
case Identifier.Agility: return "Agility increases armor";
case Identifier.Intelligence: return "Intelligence increases mana";
case Identifier.Damage: return "Damage adds to the amount of damage done in combat";
case Identifier.Crit: return "Crit increases the chance of landing a critical strike";
case Identifier.Armor: return "Armor protects from damage";
case Identifier.Health: return "Health prolongs life";
case Identifier.Mana: return "Mana increases the number of spells that can be cast";
}
return null;
}
/// <summary>
/// Comparison function for sorting armor. Armor value will show up first, followed by damage.
/// </summary>
static public int CompareArmor (InvStat a, InvStat b)
{
int ia = (int)a.id;
int ib = (int)b.id;
if (a.id == Identifier.Armor) ia -= 10000;
else if (a.id == Identifier.Damage) ia -= 5000;
if (b.id == Identifier.Armor) ib -= 10000;
else if (b.id == Identifier.Damage) ib -= 5000;
if (a.amount < 0) ia += 1000;
if (b.amount < 0) ib += 1000;
if (a.modifier == Modifier.Percent) ia += 100;
if (b.modifier == Modifier.Percent) ib += 100;
// Not using ia.CompareTo(ib) here because Flash export doesn't understand that
if (ia < ib) return -1;
if (ia > ib) return 1;
return 0;
}
/// <summary>
/// Comparison function for sorting weapons. Damage value will show up first, followed by armor.
/// </summary>
static public int CompareWeapon (InvStat a, InvStat b)
{
int ia = (int)a.id;
int ib = (int)b.id;
if (a.id == Identifier.Damage) ia -= 10000;
else if (a.id == Identifier.Armor) ia -= 5000;
if (b.id == Identifier.Damage) ib -= 10000;
else if (b.id == Identifier.Armor) ib -= 5000;
if (a.amount < 0) ia += 1000;
if (b.amount < 0) ib += 1000;
if (a.modifier == Modifier.Percent) ia += 100;
if (b.modifier == Modifier.Percent) ib += 100;
if (ia < ib) return -1;
if (ia > ib) return 1;
return 0;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/System/InvStat.cs
|
C#
|
asf20
| 3,204
|
using UnityEngine;
[AddComponentMenu("NGUI/Examples/Item Attachment Point")]
public class InvAttachmentPoint : MonoBehaviour
{
/// <summary>
/// Item slot that this attachment point covers.
/// </summary>
public InvBaseItem.Slot slot;
GameObject mPrefab;
GameObject mChild;
/// <summary>
/// Attach an instance of the specified game object.
/// </summary>
public GameObject Attach (GameObject prefab)
{
if (mPrefab != prefab)
{
mPrefab = prefab;
// Remove the previous child
if (mChild != null) Destroy(mChild);
// If we have something to create, let's do so now
if (mPrefab != null)
{
// Create a new instance of the game object
Transform t = transform;
mChild = Instantiate(mPrefab, t.position, t.rotation) as GameObject;
// Parent the child to this object
Transform ct = mChild.transform;
ct.parent = t;
// Reset the pos/rot/scale, just in case
ct.localPosition = Vector3.zero;
ct.localRotation = Quaternion.identity;
ct.localScale = Vector3.one;
}
}
return mChild;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Examples/Scripts/InventorySystem/System/InvAttachmentPoint.cs
|
C#
|
asf20
| 1,111
|