Skip to content

Instantly share code, notes, and snippets.

@miguelSantirso
Created June 6, 2015 16:32
Show Gist options
  • Save miguelSantirso/c8dc76c3ac8c8adf1106 to your computer and use it in GitHub Desktop.
Save miguelSantirso/c8dc76c3ac8c8adf1106 to your computer and use it in GitHub Desktop.
[Unity] Use a 2D collider to filter clicks on any Unity UI component (Button, Image, etc...)
using UnityEngine;
using UnityEngine.UI;
[RequireComponent (typeof (RectTransform), typeof (Collider2D))]
public class Collider2DRaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
Collider2D myCollider;
RectTransform rectTransform;
void Awake ()
{
myCollider = GetComponent<Collider2D>();
rectTransform = GetComponent<RectTransform>();
}
#region ICanvasRaycastFilter implementation
public bool IsRaycastLocationValid (Vector2 screenPos, Camera eventCamera)
{
var worldPoint = Vector3.zero;
var isInside = RectTransformUtility.ScreenPointToWorldPointInRectangle(
rectTransform,
screenPos,
eventCamera,
out worldPoint
);
if (isInside)
isInside = myCollider.OverlapPoint(worldPoint);
return isInside;
}
#endregion
}
@DryreL
Copy link

DryreL commented Jun 23, 2021

Thanks! Really useful script

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment