Last active
January 5, 2022 16:26
-
-
Save Sov3rain/412c42d538e341b018341691d9e684a6 to your computer and use it in GitHub Desktop.
[Unity] Find if a touch is over a UI element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class TouchHelper | |
{ | |
// OG version: https://www.reddit.com/r/Unity3D/comments/6o9zsy/comment/dkgxa1i/?utm_source=share&utm_medium=web2x&context=3 | |
public static bool IsOverUI() | |
{ | |
PointerEventData pointerData = new PointerEventData(EventSystem.current); | |
pointerData.position = Input.mousePosition; | |
List<RaycastResult> results = new List<RaycastResult>(); | |
EventSystem.current.RaycastAll(pointerData, results); | |
if (results.Count > 0) | |
{ | |
for (int i = 0; i < results.Count; i++) | |
{ | |
if (results[i].gameObject.GetComponent<CanvasRenderer>()) | |
{ | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
// Better version, checking over a layer is more optimized than getting a component. | |
// Caching the results over allocating new lists every frame is better too. | |
static readonly List<RaycastResult> _results = new List<RaycastResult>(); | |
static readonly PointerEventData _pointerEventData = new PointerEventData(EventSystem.current); | |
static public bool IsTouchOverUI(int touchId) | |
{ | |
_results.Clear(); | |
_pointerEventData.position = Input.GetTouch(touchId).position; | |
EventSystem.current.RaycastAll(_pointerEventData, _results); | |
if (_results.Count > 0) | |
for (int i = 0; i < _results.Count; i++) | |
if (_results[i].gameObject.layer == 5) // UI layer is always 5 | |
return true; | |
return false; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment