Created
June 6, 2015 16:32
-
-
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...)
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! Really useful script