判断是否点击到UI上可以使用UnityEngine.EventSystem下的EventSystem.current.IsPointerOverGameObject()检测,但是在移动端无法使用该方法,以下三种方法可以解决:


第一种方法:

如果使用的是Touch类进行移动端手势判定,则可以使用IsPointerOverGameObject()的重载方法,传入触碰的手指Id

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

第二种方法:

如果使用的是Input类进行的移动端手势判定,则可以通过UI事件发射射线进行检测

public static 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;
}
public bool IsPointerOverUIObject(Vector2 screenPosition)
{
    PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
    eventDataCurrentPosition.position = new Vector2(screenPosition.x, screenPosition.y);

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

第三种方法:

通过画布上的GraphicRaycaster组件发射射线进行检测

public bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition) 
{
    PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
    eventDataCurrentPosition.position = screenPosition;
    GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();
    
    List<RaycastResult> results = new List<RaycastResult>();
    uiRaycaster.Raycast(eventDataCurrentPosition, results);
    return results.Count > 0;
}