| | 1 | | using System.Collections.Generic; |
| | 2 | | using System.Linq; |
| | 3 | | using UnityEngine; |
| | 4 | | using UnityEngine.EventSystems; |
| | 5 | |
|
| | 6 | | namespace UIComponents.ContextMenu |
| | 7 | | { |
| | 8 | | [RequireComponent(typeof(RectTransform))] |
| | 9 | | public abstract class ContextMenuComponentView : BaseComponentView |
| | 10 | | { |
| 246 | 11 | | [SerializeField] private bool hideWhenClickedOutsideArea = true; |
| | 12 | |
|
| 246 | 13 | | private readonly Vector3[] corners = new Vector3[4]; |
| | 14 | |
|
| | 15 | | private RectTransform rectTransform; |
| | 16 | |
|
| 0 | 17 | | public Transform[] HidingHierarchyTransforms { get; set; } |
| | 18 | |
|
| | 19 | | public override void Awake() |
| | 20 | | { |
| 16 | 21 | | base.Awake(); |
| | 22 | |
|
| 16 | 23 | | rectTransform = GetComponent<RectTransform>(); |
| 16 | 24 | | } |
| | 25 | |
|
| | 26 | | public virtual void Update() |
| | 27 | | { |
| 3 | 28 | | if (hideWhenClickedOutsideArea) |
| 3 | 29 | | HideIfClickedOutside(); |
| 3 | 30 | | } |
| | 31 | |
|
| | 32 | | public void ClampPositionToScreenBorders(Vector2 position) |
| | 33 | | { |
| 2 | 34 | | rectTransform.position = position; |
| 2 | 35 | | rectTransform.GetWorldCorners(corners); |
| | 36 | |
|
| 2 | 37 | | Bounds bounds = new Bounds(); |
| 2 | 38 | | bounds.SetMinMax(corners[1], corners[3]); |
| | 39 | |
|
| 2 | 40 | | Vector3 offset = Vector3.zero; |
| | 41 | |
|
| 2 | 42 | | offset.x -= Mathf.Min(0f, bounds.min.x); |
| 2 | 43 | | offset.y -= Mathf.Min(0f, bounds.max.y); |
| 2 | 44 | | offset.x -= Mathf.Max(0f, bounds.max.x - Screen.width); |
| 2 | 45 | | offset.y -= Mathf.Max(0f, bounds.min.y - Screen.height); |
| | 46 | |
|
| 2 | 47 | | rectTransform.position += offset; |
| 2 | 48 | | } |
| | 49 | |
|
| | 50 | | private void HideIfClickedOutside() |
| | 51 | | { |
| 6 | 52 | | if (!Input.GetMouseButtonDown(0)) return; |
| | 53 | |
|
| 0 | 54 | | var pointerEventData = new PointerEventData(EventSystem.current) |
| | 55 | | { |
| | 56 | | position = Input.mousePosition, |
| | 57 | | }; |
| | 58 | |
|
| 0 | 59 | | var raycastResults = new List<RaycastResult>(); |
| 0 | 60 | | EventSystem.current.RaycastAll(pointerEventData, raycastResults); |
| | 61 | |
|
| 0 | 62 | | if (raycastResults.All(result => |
| | 63 | | { |
| 0 | 64 | | if (HidingHierarchyTransforms != null) |
| | 65 | | { |
| 0 | 66 | | foreach (var t in HidingHierarchyTransforms) |
| 0 | 67 | | if (t == result.gameObject.transform) |
| 0 | 68 | | return false; |
| | 69 | |
|
| 0 | 70 | | return true; |
| | 71 | | } |
| | 72 | |
|
| 0 | 73 | | return result.gameObject.transform != rectTransform |
| | 74 | | && !result.gameObject.transform.IsChildOf(rectTransform); |
| | 75 | | })) |
| | 76 | | { |
| 0 | 77 | | Hide(); |
| | 78 | | } |
| 0 | 79 | | } |
| | 80 | | } |
| | 81 | | } |