在Unity3d中,如何检测UI的触摸事件?

10

我正在开发一款Unity3d移动应用。但我遇到了一个问题:如何检测UI上的触摸事件?

我尝试了以下方法(但它并不起作用):

UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject();

以及这个:

private static List<RaycastResult> tempRaycastResults = new List<RaycastResult>();

public bool PointIsOverUI(float x, float y)
{
    var eventDataCurrentPosition = new PointerEventData(EventSystem.current);

    eventDataCurrentPosition.position = new Vector2(x, y);

    tempRaycastResults.Clear();

    EventSystem.current.RaycastAll(eventDataCurrentPosition, tempRaycastResults);
    
    return tempRaycastResults.Count > 0;
}

3个回答

23

对于移动设备,您需要将触摸的id传递给IsPointerOverGameObject

foreach (Touch touch in Input.touches)
{
    int id = touch.fingerId;
    if (EventSystem.current.IsPointerOverGameObject(id))
    {
        // ui touched
    }
}

1
最近我遇到了这个问题。奇怪的是,在我的项目中,Unity 5.3.x 中的 EventSystem.current.IsPointerOverGameObject() 在 iOS(和 Android!)上运行良好,但至少在 Unity 5.4.0f3 中,我必须为 iOS 添加一个 id(在我的情况下,0 是可以的),但对于 Android 则不需要。 - livingtech

1

Please try this :

// for Android check differently :

if(EventSystem.current.IsPointerOverGameObject(0) return false;

// for windows check as usual :

if (EventSystem.current.IsPointerOverGameObject())
    return false;

如果您在不带参数的情况下使用IsPointerOverGameObject(),它会指向“左键”(pointerId = -1);因此,当您在触摸时使用IsPointerOverGameObject时,应考虑向其传递一个pointerId。 https://docs.unity3d.com/2018.2/Documentation/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html - CrandellWS

0
将此代码添加到可点击的对象中。
private MyUIHoverListener uiListener;
private Vector3 mousePos;
    
private void OnMouseDown()
{
    mousePos = Input.mousePosition;
    Debug.Log(Input.mousePosition);
}
private void OnMouseUp()
{
    //this part helps to not trigger object when dragging
    mousePos -=  Input.mousePosition;
    //Debug.Log(mousePos);
    
    if(mousePos.x < 3 && mousePos.y < 3 
        && mousePos.z < 3 && mousePos.x > -3 
        && mousePos.y > -3 && mousePos.z > -3)
    {
        //Debug.Log("NOT MOVED");
        if (!GameMan.ObjectClickBlocker)
        {
            if (uiListener.IsUIOverride)
            {
                //Debug.Log("Cancelled OnMouseDown! A UI element has override this object!");
            }
            else
            {
                // Debug.Log("Object OnMouseDown");
                StartCoroutine(LoadThisBuilding(0));
                ToggleBuildingMenu();  
            }
        }
    }
}

将此代码添加到可点击对象前面的对象上:
public class MyUIHoverListener : MonoBehaviour
{
    [SerializeField]
    public bool IsUIOverride { get; private set; }

    void Update()
    {
        // It will turn true if hovering any UI Elements
        IsUIOverride = EventSystem.current.IsPointerOverGameObject();
    }
    void OnDisable()
    {
        IsUIOverride = false;}
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接