Unity 判断是否点击到UI上的方法

在3D场景中,既有UI,又有物体的交互时,同时点击既会触发UI交互,又会触发物体交互,而我们往往只需要单个交互,那么此时就要区分触碰到的是UI,还是物体了。

方法就是先判断点击是否点击在UI上,假如点击到UI上就处理UI交互,不处理物体交互,当没有点击到UI时,只点击到物体上,就处理物体交互。如此这般就能完美解决上面的交互问题,具体这样实现:

bool isClickUI;
void Update{

//判断点击是否触控在UI上的方法
if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
{
#if IPHONE || ANDROID
	if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
    if (EventSystem.current.IsPointerOverGameObject())
    {
         isClickUI = true;
         Debug.Log("当前触摸在UI上");
     }
#endif
     else
     {
         isClickUI = false;
         Debug.Log("当前没有触摸在UI上");
     }
}

if(isClickUI)
{
     //处理UI事件
}
else
{
    //处理非UI事件,如鼠标点击发射射线触控物体的交互
    Ray ray = cam.ScreenPointToRay(Input.mousePosition);
    RaycastHit hitInfo = new RaycastHit();
    if (Physics.Raycast(ray, out hitInfo))
    {
        //处理点击与物体交互事件
    }
}
}

主要方法是使用 EventSystem.current.IsPointerOverGameObject(),然后通过定义一个布尔值作为是否点击在UI上的判断,并由此进行相关处理。

猜你喜欢

转载自blog.csdn.net/mr_five55/article/details/135350389
今日推荐