【问题标题】:In Unity3d How detect touch on UI or not?在 Unity3d 中如何检测 UI 上的触摸?
【发布时间】:2022-05-03 14:39:42
【问题描述】:

在制作 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;
}

【问题讨论】:

标签: unity3d touch


【解决方案1】:

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

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

【讨论】:

  • 我最近遇到了这个问题。奇怪的是,在我的项目中,在 Unity 5.3.x EventSystem.current.IsPointerOverGameObject() 在 iOS(和 Android!)中运行良好,但至少在 Unity 5.4.0f3 中,我必须添加一个 id(在我的情况下 0 很好)适用于 iOS,但不适用于 Android。
【解决方案2】:

请试试这个:

// for Android check differently :

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

// for windows check as usual :

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

【讨论】:

【解决方案3】:

将此添加到可点击对象

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;}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-19
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    相关资源
    最近更新 更多