File size: 17,666 Bytes
18a519f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | using System.Collections.Generic;
using System.Text;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor.AnimatedValues;
namespace UnityEditor.UI
{
[CustomEditor(typeof(Selectable), true)]
/// <summary>
/// Custom Editor for the Selectable Component.
/// Extend this class to write a custom editor for a component derived from Selectable.
/// </summary>
public class SelectableEditor : Editor
{
SerializedProperty m_Script;
SerializedProperty m_InteractableProperty;
SerializedProperty m_TargetGraphicProperty;
SerializedProperty m_TransitionProperty;
SerializedProperty m_ColorBlockProperty;
SerializedProperty m_SpriteStateProperty;
SerializedProperty m_AnimTriggerProperty;
SerializedProperty m_NavigationProperty;
GUIContent m_VisualizeNavigation = EditorGUIUtility.TrTextContent("Visualize", "Show navigation flows between selectable UI elements.");
AnimBool m_ShowColorTint = new AnimBool();
AnimBool m_ShowSpriteTrasition = new AnimBool();
AnimBool m_ShowAnimTransition = new AnimBool();
private static List<SelectableEditor> s_Editors = new List<SelectableEditor>();
private static bool s_ShowNavigation = false;
private static string s_ShowNavigationKey = "SelectableEditor.ShowNavigation";
// Whenever adding new SerializedProperties to the Selectable and SelectableEditor
// Also update this guy in OnEnable. This makes the inherited classes from Selectable not require a CustomEditor.
private string[] m_PropertyPathToExcludeForChildClasses;
protected virtual void OnEnable()
{
m_Script = serializedObject.FindProperty("m_Script");
m_InteractableProperty = serializedObject.FindProperty("m_Interactable");
m_TargetGraphicProperty = serializedObject.FindProperty("m_TargetGraphic");
m_TransitionProperty = serializedObject.FindProperty("m_Transition");
m_ColorBlockProperty = serializedObject.FindProperty("m_Colors");
m_SpriteStateProperty = serializedObject.FindProperty("m_SpriteState");
m_AnimTriggerProperty = serializedObject.FindProperty("m_AnimationTriggers");
m_NavigationProperty = serializedObject.FindProperty("m_Navigation");
m_PropertyPathToExcludeForChildClasses = new[]
{
m_Script.propertyPath,
m_NavigationProperty.propertyPath,
m_TransitionProperty.propertyPath,
m_ColorBlockProperty.propertyPath,
m_SpriteStateProperty.propertyPath,
m_AnimTriggerProperty.propertyPath,
m_InteractableProperty.propertyPath,
m_TargetGraphicProperty.propertyPath,
};
var trans = GetTransition(m_TransitionProperty);
m_ShowColorTint.value = (trans == Selectable.Transition.ColorTint);
m_ShowSpriteTrasition.value = (trans == Selectable.Transition.SpriteSwap);
m_ShowAnimTransition.value = (trans == Selectable.Transition.Animation);
m_ShowColorTint.valueChanged.AddListener(Repaint);
m_ShowSpriteTrasition.valueChanged.AddListener(Repaint);
s_Editors.Add(this);
RegisterStaticOnSceneGUI();
s_ShowNavigation = EditorPrefs.GetBool(s_ShowNavigationKey);
}
protected virtual void OnDisable()
{
m_ShowColorTint.valueChanged.RemoveListener(Repaint);
m_ShowSpriteTrasition.valueChanged.RemoveListener(Repaint);
s_Editors.Remove(this);
RegisterStaticOnSceneGUI();
}
private void RegisterStaticOnSceneGUI()
{
SceneView.duringSceneGui -= StaticOnSceneGUI;
if (s_Editors.Count > 0)
SceneView.duringSceneGui += StaticOnSceneGUI;
}
static Selectable.Transition GetTransition(SerializedProperty transition)
{
return (Selectable.Transition)transition.enumValueIndex;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(m_InteractableProperty);
var trans = GetTransition(m_TransitionProperty);
var graphic = m_TargetGraphicProperty.objectReferenceValue as Graphic;
if (graphic == null)
graphic = (target as Selectable).GetComponent<Graphic>();
var animator = (target as Selectable).GetComponent<Animator>();
m_ShowColorTint.target = (!m_TransitionProperty.hasMultipleDifferentValues && trans == Button.Transition.ColorTint);
m_ShowSpriteTrasition.target = (!m_TransitionProperty.hasMultipleDifferentValues && trans == Button.Transition.SpriteSwap);
m_ShowAnimTransition.target = (!m_TransitionProperty.hasMultipleDifferentValues && trans == Button.Transition.Animation);
EditorGUILayout.PropertyField(m_TransitionProperty);
++EditorGUI.indentLevel;
{
if (trans == Selectable.Transition.ColorTint || trans == Selectable.Transition.SpriteSwap)
{
EditorGUILayout.PropertyField(m_TargetGraphicProperty);
}
switch (trans)
{
case Selectable.Transition.ColorTint:
if (graphic == null)
EditorGUILayout.HelpBox("You must have a Graphic target in order to use a color transition.", MessageType.Warning);
break;
case Selectable.Transition.SpriteSwap:
if (graphic as Image == null)
EditorGUILayout.HelpBox("You must have a Image target in order to use a sprite swap transition.", MessageType.Warning);
break;
}
if (EditorGUILayout.BeginFadeGroup(m_ShowColorTint.faded))
{
EditorGUILayout.PropertyField(m_ColorBlockProperty);
}
EditorGUILayout.EndFadeGroup();
if (EditorGUILayout.BeginFadeGroup(m_ShowSpriteTrasition.faded))
{
EditorGUILayout.PropertyField(m_SpriteStateProperty);
}
EditorGUILayout.EndFadeGroup();
if (EditorGUILayout.BeginFadeGroup(m_ShowAnimTransition.faded))
{
EditorGUILayout.PropertyField(m_AnimTriggerProperty);
if (animator == null || animator.runtimeAnimatorController == null)
{
Rect buttonRect = EditorGUILayout.GetControlRect();
buttonRect.xMin += EditorGUIUtility.labelWidth;
if (GUI.Button(buttonRect, "Auto Generate Animation", EditorStyles.miniButton))
{
var controller = GenerateSelectableAnimatorContoller((target as Selectable).animationTriggers, target as Selectable);
if (controller != null)
{
if (animator == null)
animator = (target as Selectable).gameObject.AddComponent<Animator>();
Animations.AnimatorController.SetAnimatorController(animator, controller);
}
}
}
}
EditorGUILayout.EndFadeGroup();
}
--EditorGUI.indentLevel;
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_NavigationProperty);
EditorGUI.BeginChangeCheck();
Rect toggleRect = EditorGUILayout.GetControlRect();
toggleRect.xMin += EditorGUIUtility.labelWidth;
s_ShowNavigation = GUI.Toggle(toggleRect, s_ShowNavigation, m_VisualizeNavigation, EditorStyles.miniButton);
if (EditorGUI.EndChangeCheck())
{
EditorPrefs.SetBool(s_ShowNavigationKey, s_ShowNavigation);
SceneView.RepaintAll();
}
// We do this here to avoid requiring the user to also write a Editor for their Selectable-derived classes.
// This way if we are on a derived class we dont draw anything else, otherwise draw the remaining properties.
ChildClassPropertiesGUI();
serializedObject.ApplyModifiedProperties();
}
// Draw the extra SerializedProperties of the child class.
// We need to make sure that m_PropertyPathToExcludeForChildClasses has all the Selectable properties and in the correct order.
// TODO: find a nicer way of doing this. (creating a InheritedEditor class that automagically does this)
private void ChildClassPropertiesGUI()
{
if (IsDerivedSelectableEditor())
return;
DrawPropertiesExcluding(serializedObject, m_PropertyPathToExcludeForChildClasses);
}
private bool IsDerivedSelectableEditor()
{
return GetType() != typeof(SelectableEditor);
}
private static Animations.AnimatorController GenerateSelectableAnimatorContoller(AnimationTriggers animationTriggers, Selectable target)
{
if (target == null)
return null;
// Where should we create the controller?
var path = GetSaveControllerPath(target);
if (string.IsNullOrEmpty(path))
return null;
// figure out clip names
var normalName = string.IsNullOrEmpty(animationTriggers.normalTrigger) ? "Normal" : animationTriggers.normalTrigger;
var highlightedName = string.IsNullOrEmpty(animationTriggers.highlightedTrigger) ? "Highlighted" : animationTriggers.highlightedTrigger;
var pressedName = string.IsNullOrEmpty(animationTriggers.pressedTrigger) ? "Pressed" : animationTriggers.pressedTrigger;
var selectedName = string.IsNullOrEmpty(animationTriggers.selectedTrigger) ? "Selected" : animationTriggers.selectedTrigger;
var disabledName = string.IsNullOrEmpty(animationTriggers.disabledTrigger) ? "Disabled" : animationTriggers.disabledTrigger;
// Create controller and hook up transitions.
var controller = Animations.AnimatorController.CreateAnimatorControllerAtPath(path);
GenerateTriggerableTransition(normalName, controller);
GenerateTriggerableTransition(highlightedName, controller);
GenerateTriggerableTransition(pressedName, controller);
GenerateTriggerableTransition(selectedName, controller);
GenerateTriggerableTransition(disabledName, controller);
AssetDatabase.ImportAsset(path);
return controller;
}
private static string GetSaveControllerPath(Selectable target)
{
var defaultName = target.gameObject.name;
var message = string.Format("Create a new animator for the game object '{0}':", defaultName);
return EditorUtility.SaveFilePanelInProject("New Animation Contoller", defaultName, "controller", message);
}
private static void SetUpCurves(AnimationClip highlightedClip, AnimationClip pressedClip, string animationPath)
{
string[] channels = { "m_LocalScale.x", "m_LocalScale.y", "m_LocalScale.z" };
var highlightedKeys = new[] { new Keyframe(0f, 1f), new Keyframe(0.5f, 1.1f), new Keyframe(1f, 1f) };
var highlightedCurve = new AnimationCurve(highlightedKeys);
foreach (var channel in channels)
AnimationUtility.SetEditorCurve(highlightedClip, EditorCurveBinding.FloatCurve(animationPath, typeof(Transform), channel), highlightedCurve);
var pressedKeys = new[] { new Keyframe(0f, 1.15f) };
var pressedCurve = new AnimationCurve(pressedKeys);
foreach (var channel in channels)
AnimationUtility.SetEditorCurve(pressedClip, EditorCurveBinding.FloatCurve(animationPath, typeof(Transform), channel), pressedCurve);
}
private static string BuildAnimationPath(Selectable target)
{
// if no target don't hook up any curves.
var highlight = target.targetGraphic;
if (highlight == null)
return string.Empty;
var startGo = highlight.gameObject;
var toFindGo = target.gameObject;
var pathComponents = new Stack<string>();
while (toFindGo != startGo)
{
pathComponents.Push(startGo.name);
// didn't exist in hierarchy!
if (startGo.transform.parent == null)
return string.Empty;
startGo = startGo.transform.parent.gameObject;
}
// calculate path
var animPath = new StringBuilder();
if (pathComponents.Count > 0)
animPath.Append(pathComponents.Pop());
while (pathComponents.Count > 0)
animPath.Append("/").Append(pathComponents.Pop());
return animPath.ToString();
}
private static AnimationClip GenerateTriggerableTransition(string name, Animations.AnimatorController controller)
{
// Create the clip
var clip = Animations.AnimatorController.AllocateAnimatorClip(name);
AssetDatabase.AddObjectToAsset(clip, controller);
// Create a state in the animatior controller for this clip
var state = controller.AddMotion(clip);
// Add a transition property
controller.AddParameter(name, AnimatorControllerParameterType.Trigger);
// Add an any state transition
var stateMachine = controller.layers[0].stateMachine;
var transition = stateMachine.AddAnyStateTransition(state);
transition.AddCondition(Animations.AnimatorConditionMode.If, 0, name);
return clip;
}
private static void StaticOnSceneGUI(SceneView view)
{
if (!s_ShowNavigation)
return;
Selectable[] selectables = Selectable.allSelectablesArray;
for (int i = 0; i < selectables.Length; i++)
{
Selectable s = selectables[i];
if (SceneManagement.StageUtility.IsGameObjectRenderedByCamera(s.gameObject, Camera.current))
DrawNavigationForSelectable(s);
}
}
private static void DrawNavigationForSelectable(Selectable sel)
{
if (sel == null)
return;
Transform transform = sel.transform;
bool active = Selection.transforms.Any(e => e == transform);
Handles.color = new Color(1.0f, 0.6f, 0.2f, active ? 1.0f : 0.4f);
DrawNavigationArrow(-Vector2.right, sel, sel.FindSelectableOnLeft());
DrawNavigationArrow(Vector2.up, sel, sel.FindSelectableOnUp());
Handles.color = new Color(1.0f, 0.9f, 0.1f, active ? 1.0f : 0.4f);
DrawNavigationArrow(Vector2.right, sel, sel.FindSelectableOnRight());
DrawNavigationArrow(-Vector2.up, sel, sel.FindSelectableOnDown());
}
const float kArrowThickness = 2.5f;
const float kArrowHeadSize = 1.2f;
private static void DrawNavigationArrow(Vector2 direction, Selectable fromObj, Selectable toObj)
{
if (fromObj == null || toObj == null)
return;
Transform fromTransform = fromObj.transform;
Transform toTransform = toObj.transform;
Vector2 sideDir = new Vector2(direction.y, -direction.x);
Vector3 fromPoint = fromTransform.TransformPoint(GetPointOnRectEdge(fromTransform as RectTransform, direction));
Vector3 toPoint = toTransform.TransformPoint(GetPointOnRectEdge(toTransform as RectTransform, -direction));
float fromSize = HandleUtility.GetHandleSize(fromPoint) * 0.05f;
float toSize = HandleUtility.GetHandleSize(toPoint) * 0.05f;
fromPoint += fromTransform.TransformDirection(sideDir) * fromSize;
toPoint += toTransform.TransformDirection(sideDir) * toSize;
float length = Vector3.Distance(fromPoint, toPoint);
Vector3 fromTangent = fromTransform.rotation * direction * length * 0.3f;
Vector3 toTangent = toTransform.rotation * -direction * length * 0.3f;
Handles.DrawBezier(fromPoint, toPoint, fromPoint + fromTangent, toPoint + toTangent, Handles.color, null, kArrowThickness);
Handles.DrawAAPolyLine(kArrowThickness, toPoint, toPoint + toTransform.rotation * (-direction - sideDir) * toSize * kArrowHeadSize);
Handles.DrawAAPolyLine(kArrowThickness, toPoint, toPoint + toTransform.rotation * (-direction + sideDir) * toSize * kArrowHeadSize);
}
private static Vector3 GetPointOnRectEdge(RectTransform rect, Vector2 dir)
{
if (rect == null)
return Vector3.zero;
if (dir != Vector2.zero)
dir /= Mathf.Max(Mathf.Abs(dir.x), Mathf.Abs(dir.y));
dir = rect.rect.center + Vector2.Scale(rect.rect.size, dir * 0.5f);
return dir;
}
}
}
|