Skip to content

Instantly share code, notes, and snippets.

@andydbc
Created November 5, 2024 23:32
Show Gist options
  • Save andydbc/41d9a101e39921e6924ff30ee6cd095c to your computer and use it in GitHub Desktop.
Save andydbc/41d9a101e39921e6924ff30ee6cd095c to your computer and use it in GitHub Desktop.
Disable a UI element when a mouse click occurs outside its bounding rectangle.
public static class UIExtensions
{
public static bool HideIfClickedOutside(this GameObject panel) {
if (Input.GetMouseButton(0) && panel.activeSelf &&
!RectTransformUtility.RectangleContainsScreenPoint(
panel.GetComponent<RectTransform>(),
Input.mousePosition,
null)) {
panel.SetActive(false);
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment