Unity

[Unity] Object 와 UI 구분하기

성엽이 2019. 10. 29. 15:10

EventSystem.IsPointerOverGameObject

public bool IsPointerOverGameObject ();

public bool IsPointerOverGameObject (int pointerId);

Parameters

pointerId Pointer (touch / mouse) ID.

 

Description

Is the pointer with the given ID over an EventSystem object?

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class MouseExample : MonoBehaviour
{
    void Update()
    {
        // Check if the left mouse button was clicked
        if (Input.GetMouseButtonDown(0))
        {
            // Check if the mouse was clicked over a UI element
            if (EventSystem.current.IsPointerOverGameObject())
            {
                Debug.Log("Clicked on the UI");
            }
        }
    }
}

If you use IsPointerOverGameObject() without a parameter, it points to the "left mouse button" (pointerId = -1);

Default 값이 왼쪽 마우스 클릭 시(-1) 인 경우이다. 매개변수가 필요없다.

 


 

when you use IsPointerOverGameObject for touch, you should consider passing a pointerId to it.

터치를 사용할 때는 pointerId 를 사용해야한다.

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class TouchExample : MonoBehaviour
{
    void Update()
    {
        // Check if there is a touch
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
            // Check if finger is over a UI element
            if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
            {
                Debug.Log("Touched the UI");
            }
        }
    }
}

Note that for touch, IsPointerOverGameObject should be used with OnMouseDown() or Input.GetMouseButtonDown(0) or Input.GetTouch(0).phase == TouchPhase.Began.

터치에서 쓸수 있는 함수 예제들.