Unity中解决IsPointerOverGameObject防UI穿透在移动端检测失败

508 阅读1分钟

一:前言

判断是否点击到UI上可以使用UnityEngine.EventSystem下的EventSystem.current.IsPointerOverGameObject方法,但是在移动端无法使用该方法,源码中也提示了在移动端需要传入特殊参数


二:解决方法

——传入触碰的手指Id

if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) 
{
    //TODO:点击在了UI上
}

——通过EventSystem总管理器发送射线

public bool IsPointerOverUIObject() 
{
    PointerEventData eventData = new PointerEventData(EventSystem.current);
    eventData.position = Input.mousePosition;

    List<RaycastResult> results = new List<RaycastResult>();
    EventSystem.current.RaycastAll(eventData, results);
    return results.Count > 0;
}

——通过单独Canvas上的GraphicRaycasters发送射线

GraphicRaycaster raycaster;
public bool IsPointerOverUIObject()
{
    PointerEventData eventData = new PointerEventData(EventSystem.current);
    eventData.position = Input.mousePosition;

    List<RaycastResult> results = new List<RaycastResult>();
    raycaster.Raycast(eventData, results);
    return results.Count > 0;
}