[Unity] Detect UI Clicks

This article can be read in about 3 minutes.
PR

The purpose

In Unity, we often need to detect when a UI element (specifically, a GameObject with a RectTransform component) has been clicked.

While it’s usually sufficient to inherit from the Button class for this purpose, there are situations where this isn’t feasible. For instance, when you need the click event to also pass through to elements beneath the UI, you’ll need to implement the click detection manually.

PR

Implementation

We can use the following functions.

bool RectangleContainsScreenPoint (RectTransform rect, Vector2 screenPoint, Camera cam);

This verifies whether screenPoint is inside rect. If it is, true is returned. When verifying against UI, there is no need to set cam.

Example

Here’s an implementation example: Validation is performed on a child object named “GameObjectName” within a MonoBehaviour-derived class.

if (Input.GetMouseButtonUp(0)) {
    var obj = tramsform.Find("GameObjectName");
    if (RectTransformUtility.RectangleContainsScreenPoint(obj.GetComponent<RectTransform>(), Input.mousePosition))
    { 
            Debug.Log ("GameObject is clicked");
    }
}
PR

Reference

RectTransformUtility-RectangleContainsScreenPoint - Unity スクリプトリファレンス
RectTransform は指定されたカメラから見たスクリーンポイントを含むか。

comment

Copied title and URL