-
Notifications
You must be signed in to change notification settings - Fork 319
Expand file tree
/
Copy pathSelectable.cs
More file actions
1312 lines (1197 loc) · 47.1 KB
/
Selectable.cs
File metadata and controls
1312 lines (1197 loc) · 47.1 KB
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using UnityEngine.Serialization;
using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
[AddComponentMenu("UI/Selectable", 70)]
[ExecuteAlways]
[SelectionBase]
[DisallowMultipleComponent]
/// <summary>
/// Simple selectable object - derived from to create a selectable control.
/// </summary>
public class Selectable
:
UIBehaviour,
IMoveHandler,
IPointerDownHandler, IPointerUpHandler,
IPointerEnterHandler, IPointerExitHandler,
ISelectHandler, IDeselectHandler
{
private static Selectable[] s_Selectables = new Selectable[10];
private static int s_SelectableCount = 0;
// If any selectable in s_Selectables are to be removed
private static bool s_IsDirty = false;
/// <summary>
/// Copy of the array of all the selectable objects currently active in the scene.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// //Displays the names of all selectable elements in the scene
/// public void GetNames()
/// {
/// foreach (Selectable selectableUI in Selectable.allSelectablesArray)
/// {
/// Debug.Log(selectableUI.name);
/// }
/// }
/// }
/// </code>
/// </example>
public static Selectable[] allSelectablesArray
{
get
{
if (s_IsDirty)
RemoveInvalidSelectables();
Selectable[] temp = new Selectable[s_SelectableCount];
Array.Copy(s_Selectables, temp, s_SelectableCount);
return temp;
}
}
/// <summary>
/// How many selectable elements are currently active.
/// </summary>
public static int allSelectableCount { get { return s_SelectableCount; } }
/// <summary>
/// A List instance of the allSelectablesArray to maintain API compatibility.
/// </summary>
[Obsolete("Replaced with allSelectablesArray to have better performance when disabling a element", false)]
public static List<Selectable> allSelectables
{
get
{
return new List<Selectable>(allSelectablesArray);
}
}
/// <summary>
/// Non allocating version for getting the all selectables.
/// If selectables.Length is less then s_SelectableCount only selectables.Length elments will be copied which
/// could result in a incomplete list of elements.
/// </summary>
/// <param name="selectables">The array to be filled with current selectable objects</param>
/// <returns>The number of element copied.</returns>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// Selectable[] m_Selectables = new Selectable[10];
///
/// //Displays the names of all selectable elements in the scene
/// public void GetNames()
/// {
/// if (m_Selectables.Length < Selectable.allSelectableCount)
/// m_Selectables = new Selectable[Selectable.allSelectableCount];
///
/// int count = Selectable.AllSelectablesNoAlloc(ref m_Selectables);
///
/// for (int i = 0; i < count; ++i)
/// {
/// Debug.Log(m_Selectables[i].name);
/// }
/// }
/// }
/// </code>
/// </example>
public static int AllSelectablesNoAlloc(Selectable[] selectables)
{
if (s_IsDirty)
RemoveInvalidSelectables();
int copyCount = selectables.Length < s_SelectableCount ? selectables.Length : s_SelectableCount;
Array.Copy(s_Selectables, selectables, copyCount);
return copyCount;
}
// Navigation information.
[FormerlySerializedAs("navigation")]
[SerializeField]
private Navigation m_Navigation = Navigation.defaultNavigation;
/// <summary>
///Transition mode for a Selectable.
/// </summary>
public enum Transition
{
/// <summary>
/// No Transition.
/// </summary>
None,
/// <summary>
/// Use an color tint transition.
/// </summary>
ColorTint,
/// <summary>
/// Use a sprite swap transition.
/// </summary>
SpriteSwap,
/// <summary>
/// Use an animation transition.
/// </summary>
Animation
}
// Type of the transition that occurs when the button state changes.
[FormerlySerializedAs("transition")]
[SerializeField]
private Transition m_Transition = Transition.ColorTint;
// Colors used for a color tint-based transition.
[FormerlySerializedAs("colors")]
[SerializeField]
private ColorBlock m_Colors = ColorBlock.defaultColorBlock;
// Sprites used for a Image swap-based transition.
[FormerlySerializedAs("spriteState")]
[SerializeField]
private SpriteState m_SpriteState;
[FormerlySerializedAs("animationTriggers")]
[SerializeField]
private AnimationTriggers m_AnimationTriggers = new AnimationTriggers();
[Tooltip("Can the Selectable be interacted with?")]
[SerializeField]
private bool m_Interactable = true;
// Graphic that will be colored.
[FormerlySerializedAs("highlightGraphic")]
[FormerlySerializedAs("m_HighlightGraphic")]
[SerializeField]
private Graphic m_TargetGraphic;
private bool m_GroupsAllowInteraction = true;
private bool m_WillRemove = false;
/// <summary>
/// The Navigation setting for this selectable object.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button button;
///
/// void Start()
/// {
/// //Set the navigation to the default value. ("Automatic" is the default value).
/// button.navigation = Navigation.defaultNavigation;
/// }
/// }
/// </code>
/// </example>
public Navigation navigation { get { return m_Navigation; } set { if (SetPropertyUtility.SetStruct(ref m_Navigation, value)) OnSetProperty(); } }
/// <summary>
/// The type of transition that will be applied to the targetGraphic when the state changes.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button btnMain;
///
/// void SomeFunction()
/// {
/// //Sets the main button's transition setting to "Color Tint".
/// btnMain.transition = Selectable.Transition.ColorTint;
/// }
/// }
/// </code>
/// </example>
public Transition transition { get { return m_Transition; } set { if (SetPropertyUtility.SetStruct(ref m_Transition, value)) OnSetProperty(); } }
/// <summary>
/// The ColorBlock for this selectable object.
/// </summary>
/// <remarks>
/// Modifications will not be visible if transition is not ColorTint.
/// </remarks>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button button;
///
/// void Start()
/// {
/// //Resets the colors in the buttons transitions.
/// button.colors = ColorBlock.defaultColorBlock;
/// }
/// }
/// </code>
/// </example>
public ColorBlock colors { get { return m_Colors; } set { if (SetPropertyUtility.SetStruct(ref m_Colors, value)) OnSetProperty(); } }
/// <summary>
/// The SpriteState for this selectable object.
/// </summary>
/// <remarks>
/// Modifications will not be visible if transition is not SpriteSwap.
/// </remarks>
/// <example>
// <code>
// using UnityEngine;
// using System.Collections;
// using UnityEngine.UI; // Required when Using UI elements.
//
// public class ExampleClass : MonoBehaviour
// {
// //Creates an instance of a sprite state (This includes the highlighted, pressed and disabled sprite.
// public SpriteState sprState = new SpriteState();
// public Button btnMain;
//
//
// void Start()
// {
// //Assigns the new sprite states to the button.
// btnMain.spriteState = sprState;
// }
// }
// </code>
// </example>
public SpriteState spriteState { get { return m_SpriteState; } set { if (SetPropertyUtility.SetStruct(ref m_SpriteState, value)) OnSetProperty(); } }
/// <summary>
/// The AnimationTriggers for this selectable object.
/// </summary>
/// <remarks>
/// Modifications will not be visible if transition is not Animation.
/// </remarks>
public AnimationTriggers animationTriggers { get { return m_AnimationTriggers; } set { if (SetPropertyUtility.SetClass(ref m_AnimationTriggers, value)) OnSetProperty(); } }
/// <summary>
/// Graphic that will be transitioned upon.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Image newImage;
/// public Button btnMain;
///
/// void SomeFunction()
/// {
/// //Displays the sprite transitions on the image when the transition to Highlighted,pressed or disabled is made.
/// btnMain.targetGraphic = newImage;
/// }
/// }
/// </code>
/// </example>
public Graphic targetGraphic { get { return m_TargetGraphic; } set { if (SetPropertyUtility.SetClass(ref m_TargetGraphic, value)) OnSetProperty(); } }
/// <summary>
/// Is this object interactable.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// public Button startButton;
/// public bool playersReady;
///
///
/// void Update()
/// {
/// // checks if the players are ready and if the start button is useable
/// if (playersReady == true && startButton.interactable == false)
/// {
/// //allows the start button to be used
/// startButton.interactable = true;
/// }
/// }
/// }
/// </code>
/// </example>
public bool interactable
{
get { return m_Interactable; }
set
{
if (SetPropertyUtility.SetStruct(ref m_Interactable, value))
{
if (!m_Interactable && EventSystem.current != null && EventSystem.current.currentSelectedGameObject == gameObject)
EventSystem.current.SetSelectedGameObject(null);
OnSetProperty();
}
}
}
private bool isPointerInside { get; set; }
private bool isPointerDown { get; set; }
private bool hasSelection { get; set; }
protected Selectable()
{}
/// <summary>
/// Convenience function that converts the referenced Graphic to a Image, if possible.
/// </summary>
public Image image
{
get { return m_TargetGraphic as Image; }
set { m_TargetGraphic = value; }
}
/// <summary>
/// Convenience function to get the Animator component on the GameObject.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // Required when Using UI elements.
///
/// public class ExampleClass : MonoBehaviour
/// {
/// private Animator buttonAnimator;
/// public Button button;
///
/// void Start()
/// {
/// //Assigns the "buttonAnimator" with the button's animator.
/// buttonAnimator = button.animator;
/// }
/// }
/// </code>
/// </example>
public Animator animator
{
get { return GetComponent<Animator>(); }
}
protected override void Awake()
{
if (m_TargetGraphic == null)
m_TargetGraphic = GetComponent<Graphic>();
}
private readonly List<CanvasGroup> m_CanvasGroupCache = new List<CanvasGroup>();
protected override void OnCanvasGroupChanged()
{
// Figure out if parent groups allow interaction
// If no interaction is alowed... then we need
// to not do that :)
var groupAllowInteraction = true;
Transform t = transform;
while (t != null)
{
t.GetComponents(m_CanvasGroupCache);
bool shouldBreak = false;
for (var i = 0; i < m_CanvasGroupCache.Count; i++)
{
// if the parent group does not allow interaction
// we need to break
if (!m_CanvasGroupCache[i].interactable)
{
groupAllowInteraction = false;
shouldBreak = true;
}
// if this is a 'fresh' group, then break
// as we should not consider parents
if (m_CanvasGroupCache[i].ignoreParentGroups)
shouldBreak = true;
}
if (shouldBreak)
break;
t = t.parent;
}
if (groupAllowInteraction != m_GroupsAllowInteraction)
{
m_GroupsAllowInteraction = groupAllowInteraction;
OnSetProperty();
}
}
/// <summary>
/// Is the object interactable.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// public Button startButton;
///
/// void Update()
/// {
/// if (!startButton.IsInteractable())
/// {
/// Debug.Log("Start Button has been Disabled");
/// }
/// }
/// }
/// </code>
/// </example>
public virtual bool IsInteractable()
{
return m_GroupsAllowInteraction && m_Interactable;
}
// Call from unity if animation properties have changed
protected override void OnDidApplyAnimationProperties()
{
OnSetProperty();
}
// Select on enable and add to the list.
protected override void OnEnable()
{
base.OnEnable();
if (s_IsDirty)
RemoveInvalidSelectables();
m_WillRemove = false;
if (s_SelectableCount == s_Selectables.Length)
{
Selectable[] temp = new Selectable[s_Selectables.Length * 2];
Array.Copy(s_Selectables, temp, s_Selectables.Length);
s_Selectables = temp;
}
s_Selectables[s_SelectableCount++] = this;
isPointerDown = false;
DoStateTransition(currentSelectionState, true);
}
protected override void OnTransformParentChanged()
{
base.OnTransformParentChanged();
// If our parenting changes figure out if we are under a new CanvasGroup.
OnCanvasGroupChanged();
}
private void OnSetProperty()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
DoStateTransition(currentSelectionState, true);
else
#endif
DoStateTransition(currentSelectionState, false);
}
// Remove from the list.
protected override void OnDisable()
{
m_WillRemove = true;
s_IsDirty = true;
InstantClearState();
base.OnDisable();
}
private static void RemoveInvalidSelectables()
{
for (int i = s_SelectableCount - 1; i >= 0; --i)
{
// Swap last element in array with element to be removed
if (s_Selectables[i] == null || s_Selectables[i].m_WillRemove)
s_Selectables[i] = s_Selectables[--s_SelectableCount];
}
s_IsDirty = false;
}
#if UNITY_EDITOR
protected override void OnValidate()
{
base.OnValidate();
m_Colors.fadeDuration = Mathf.Max(m_Colors.fadeDuration, 0.0f);
// OnValidate can be called before OnEnable, this makes it unsafe to access other components
// since they might not have been initialized yet.
// OnSetProperty potentially access Animator or Graphics. (case 618186)
if (isActiveAndEnabled)
{
if (!interactable && EventSystem.current != null && EventSystem.current.currentSelectedGameObject == gameObject)
EventSystem.current.SetSelectedGameObject(null);
// Need to clear out the override image on the target...
DoSpriteSwap(null);
// If the transition mode got changed, we need to clear all the transitions, since we don't know what the old transition mode was.
StartColorTween(Color.white, true);
TriggerAnimation(m_AnimationTriggers.normalTrigger);
// And now go to the right state.
DoStateTransition(currentSelectionState, true);
}
}
protected override void Reset()
{
m_TargetGraphic = GetComponent<Graphic>();
}
#endif // if UNITY_EDITOR
protected SelectionState currentSelectionState
{
get
{
if (!IsInteractable())
return SelectionState.Disabled;
if (isPointerDown && isPointerInside)
return SelectionState.Pressed;
if (hasSelection)
return SelectionState.Selected;
if (isPointerInside)
return SelectionState.Highlighted;
return SelectionState.Normal;
}
}
protected virtual void InstantClearState()
{
string triggerName = m_AnimationTriggers.normalTrigger;
isPointerInside = false;
isPointerDown = false;
hasSelection = false;
switch (m_Transition)
{
case Transition.ColorTint:
StartColorTween(Color.white, true);
break;
case Transition.SpriteSwap:
DoSpriteSwap(null);
break;
case Transition.Animation:
TriggerAnimation(triggerName);
break;
}
}
/// <summary>
/// Transition the Selectable to the entered state.
/// </summary>
/// <param name="state">State to transition to</param>
/// <param name="instant">Should the transition occur instantly.</param>
protected virtual void DoStateTransition(SelectionState state, bool instant)
{
if (!gameObject.activeInHierarchy)
return;
Color tintColor;
Sprite transitionSprite;
string triggerName;
switch (state)
{
case SelectionState.Normal:
tintColor = m_Colors.normalColor;
transitionSprite = null;
triggerName = m_AnimationTriggers.normalTrigger;
break;
case SelectionState.Highlighted:
tintColor = m_Colors.highlightedColor;
transitionSprite = m_SpriteState.highlightedSprite;
triggerName = m_AnimationTriggers.highlightedTrigger;
break;
case SelectionState.Pressed:
tintColor = m_Colors.pressedColor;
transitionSprite = m_SpriteState.pressedSprite;
triggerName = m_AnimationTriggers.pressedTrigger;
break;
case SelectionState.Selected:
tintColor = m_Colors.selectedColor;
transitionSprite = m_SpriteState.selectedSprite;
triggerName = m_AnimationTriggers.selectedTrigger;
break;
case SelectionState.Disabled:
tintColor = m_Colors.disabledColor;
transitionSprite = m_SpriteState.disabledSprite;
triggerName = m_AnimationTriggers.disabledTrigger;
break;
default:
tintColor = Color.black;
transitionSprite = null;
triggerName = string.Empty;
break;
}
switch (m_Transition)
{
case Transition.ColorTint:
StartColorTween(tintColor * m_Colors.colorMultiplier, instant);
break;
case Transition.SpriteSwap:
DoSpriteSwap(transitionSprite);
break;
case Transition.Animation:
TriggerAnimation(triggerName);
break;
}
}
/// <summary>
/// An enumeration of selected states of objects
/// </summary>
protected enum SelectionState
{
/// <summary>
/// The UI object can be selected.
/// </summary>
Normal,
/// <summary>
/// The UI object is highlighted.
/// </summary>
Highlighted,
/// <summary>
/// The UI object is pressed.
/// </summary>
Pressed,
/// <summary>
/// The UI object is selected
/// </summary>
Selected,
/// <summary>
/// The UI object cannot be selected.
/// </summary>
Disabled,
}
// Selection logic
/// <summary>
/// Finds the selectable object next to this one.
/// </summary>
/// <remarks>
/// The direction is determined by a Vector3 variable.
/// </remarks>
/// <param name="dir">The direction in which to search for a neighbouring Selectable object.</param>
/// <returns>The neighbouring Selectable object. Null if none found.</returns>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class ExampleClass : MonoBehaviour
/// {
/// //Sets the direction as "Up" (Y is in positive).
/// public Vector3 direction = new Vector3(0, 1, 0);
/// public Button btnMain;
///
/// public void Start()
/// {
/// //Finds and assigns the selectable above the main button
/// Selectable newSelectable = btnMain.FindSelectable(direction);
///
/// Debug.Log(newSelectable.name);
/// }
/// }
/// </code>
/// </example>
public Selectable FindSelectable(Vector3 dir)
{
dir = dir.normalized;
Vector3 localDir = Quaternion.Inverse(transform.rotation) * dir;
Vector3 pos = transform.TransformPoint(GetPointOnRectEdge(transform as RectTransform, localDir));
float maxScore = Mathf.NegativeInfinity;
Selectable bestPick = null;
if (s_IsDirty)
RemoveInvalidSelectables();
for (int i = 0; i < s_SelectableCount; ++i)
{
Selectable sel = s_Selectables[i];
if (sel == this)
continue;
if (!sel.IsInteractable() || sel.navigation.mode == Navigation.Mode.None)
continue;
#if UNITY_EDITOR
// Apart from runtime use, FindSelectable is used by custom editors to
// draw arrows between different selectables. For scene view cameras,
// only selectables in the same stage should be considered.
if (Camera.current != null && !UnityEditor.SceneManagement.StageUtility.IsGameObjectRenderedByCamera(sel.gameObject, Camera.current))
continue;
#endif
var selRect = sel.transform as RectTransform;
Vector3 selCenter = selRect != null ? (Vector3)selRect.rect.center : Vector3.zero;
Vector3 myVector = sel.transform.TransformPoint(selCenter) - pos;
// Value that is the distance out along the direction.
float dot = Vector3.Dot(dir, myVector);
// Skip elements that are in the wrong direction or which have zero distance.
// This also ensures that the scoring formula below will not have a division by zero error.
if (dot <= 0)
continue;
// This scoring function has two priorities:
// - Score higher for positions that are closer.
// - Score higher for positions that are located in the right direction.
// This scoring function combines both of these criteria.
// It can be seen as this:
// Dot (dir, myVector.normalized) / myVector.magnitude
// The first part equals 1 if the direction of myVector is the same as dir, and 0 if it's orthogonal.
// The second part scores lower the greater the distance is by dividing by the distance.
// The formula below is equivalent but more optimized.
//
// If a given score is chosen, the positions that evaluate to that score will form a circle
// that touches pos and whose center is located along dir. A way to visualize the resulting functionality is this:
// From the position pos, blow up a circular balloon so it grows in the direction of dir.
// The first Selectable whose center the circular balloon touches is the one that's chosen.
float score = dot / myVector.sqrMagnitude;
if (score > maxScore)
{
maxScore = score;
bestPick = sel;
}
}
return bestPick;
}
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;
}
// Convenience function -- change the selection to the specified object if it's not null and happens to be active.
void Navigate(AxisEventData eventData, Selectable sel)
{
if (sel != null && sel.IsActive())
eventData.selectedObject = sel.gameObject;
}
/// <summary>
/// Find the selectable object to the left of this one.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button btnMain;
///
/// // Disables the selectable UI element directly to the left of the Start Button
/// public void IgnoreSelectables()
/// {
/// //Finds the selectable UI element to the left the start button and assigns it to a variable of type "Selectable"
/// Selectable secondButton = startButton.FindSelectableOnLeft();
/// //Disables interaction with the selectable UI element
/// secondButton.interactable = false;
/// }
/// }
/// </code>
/// </example>
public virtual Selectable FindSelectableOnLeft()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnLeft;
}
if ((m_Navigation.mode & Navigation.Mode.Horizontal) != 0)
{
return FindSelectable(transform.rotation * Vector3.left);
}
return null;
}
/// <summary>
/// Find the selectable object to the right of this one.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button btnMain;
///
/// // Disables the selectable UI element directly to the right the Start Button
/// public void IgnoreSelectables()
/// {
/// //Finds the selectable UI element to the right the start button and assigns it to a variable of type "Selectable"
/// Selectable secondButton = startButton.FindSelectableOnRight();
/// //Disables interaction with the selectable UI element
/// secondButton.interactable = false;
/// }
/// }
/// </code>
/// </example>
public virtual Selectable FindSelectableOnRight()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnRight;
}
if ((m_Navigation.mode & Navigation.Mode.Horizontal) != 0)
{
return FindSelectable(transform.rotation * Vector3.right);
}
return null;
}
/// <summary>
/// The Selectable object above current
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class ExampleClass : MonoBehaviour
/// {
/// public Button btnMain;
///
/// // Disables the selectable UI element directly above the Start Button
/// public void IgnoreSelectables()
/// {
/// //Finds the selectable UI element above the start button and assigns it to a variable of type "Selectable"
/// Selectable secondButton = startButton.FindSelectableOnUp();
/// //Disables interaction with the selectable UI element
/// secondButton.interactable = false;
/// }
/// }
/// </code>
/// </example>
public virtual Selectable FindSelectableOnUp()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnUp;
}
if ((m_Navigation.mode & Navigation.Mode.Vertical) != 0)
{
return FindSelectable(transform.rotation * Vector3.up);
}
return null;
}
/// <summary>
/// Find the selectable object below this one.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI; // required when using UI elements in scripts
///
/// public class Example : MonoBehaviour
/// {
/// public Button startButton;
///
/// // Disables the selectable UI element directly below the Start Button
/// public void IgnoreSelectables()
/// {
/// //Finds the selectable UI element below the start button and assigns it to a variable of type "Selectable"
/// Selectable secondButton = startButton.FindSelectableOnDown();
/// //Disables interaction with the selectable UI element
/// secondButton.interactable = false;
/// }
/// }
/// </code>
/// </example>
public virtual Selectable FindSelectableOnDown()
{
if (m_Navigation.mode == Navigation.Mode.Explicit)
{
return m_Navigation.selectOnDown;
}
if ((m_Navigation.mode & Navigation.Mode.Vertical) != 0)
{
return FindSelectable(transform.rotation * Vector3.down);
}
return null;
}
/// <summary>
/// Determine in which of the 4 move directions the next selectable object should be found.
/// </summary>
/// <example>
/// <code>
/// using UnityEngine;
/// using System.Collections;
/// using UnityEngine.UI;
/// using UnityEngine.EventSystems;// Required when using Event data.
///
/// public class ExampleClass : MonoBehaviour, IMoveHandler
/// {
/// //When the focus moves to another selectable object, Invoke this Method.
/// public void OnMove(AxisEventData eventData)
/// {
/// //Assigns the move direction and the raw input vector representing the direction from the event data.
/// MoveDirection moveDir = eventData.moveDir;
/// Vector2 moveVector = eventData.moveVector;
///
/// //Displays the information in the console
/// Debug.Log(moveDir + ", " + moveVector);
/// }
/// }
/// </code>
/// </example>
public virtual void OnMove(AxisEventData eventData)
{