Things I want to do
This code detects when a UI element (more precisely, a GameObject with a RectTransform component) is clicked in Unity.
Normally, you would just inherit from Button, but when that’s not possible (for example, when you need to pass the event through to the bottom), you need to detect when a click has occurred yourself.
implementation
Use the following function.
bool RectangleContainsScreenPoint (RectTransform rect, Vector2 screenPoint, Camera cam);
This function checks if screenPoint is inside the rect. It returns true if it is.
When testing on the UI, cam does not need to be configured.
Specific example
An example implementation is shown below.
The class inherits from MonoBehaviour and performs validation on objects whose child name is ‘GameObjectName’.
if (Input.GetMouseButtonUp(0)) {
var obj = tramsform.Find("GameObjectName");
if (RectTransformUtility.RectangleContainsScreenPoint(obj.GetComponent<RectTransform>(), Input.mousePosition))
{
Debug.Log ("GameObject is clicked");
}
}Websites I used as references
RectTransformUtility-RectangleContainsScreenPoint - Unity スクリプトリファレンス
RectTransform は指定されたカメラから見たスクリーンポイントを含むか。


コメント