在Unity3d中如何检测UI上的触摸?

时间:2015-10-23 11:34:39

标签: unity3d touch

制作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 个答案:

答案 0 :(得分:7)

对于移动设备,您需要将Touch的ID传递给 IsPointerOverGameObject

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

答案 1 :(得分:0)

请尝试:

// for Android check differently :

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

// for windows check as usual :

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

答案 2 :(得分: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;}
}