Skip to content

Instantly share code, notes, and snippets.

@Sov3rain
Last active January 5, 2022 16:26
Show Gist options
  • Save Sov3rain/412c42d538e341b018341691d9e684a6 to your computer and use it in GitHub Desktop.
Save Sov3rain/412c42d538e341b018341691d9e684a6 to your computer and use it in GitHub Desktop.
[Unity] Find if a touch is over a UI element
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