繁体   English   中英

Unity - Input.GetMouseButtonDown

[英]Unity - Input.GetMouseButtonDown

我创建了一个脚本,通过点击智能手机显示屏,一个对象被激活。 我使用Input.GetMouseButtonDown(0)来检查是否在显示屏上进行了点击。 该脚本工作正常,但我有一个问题:如果我在场景中插入一个按钮,单击该按钮我会同时收到该按钮的单击和Input.GetMouseButtonDown函数的单击。 我怎么能“分开”两次触摸?

// Example
void Update()
{
    if (Input.GetMouseButtonDown(0))
    myObject.SetActive(true); 
}
            
public void PauseButton()
{
    // Open Pause Panel
            
}

我正在考虑删除“Input.GetMouseButtonDown (0)”并使用一个不可见的按钮并在我需要的显示部分上调整它的大小。

将标签添加到您的 UI 按钮,例如: "UI"

下面的函数告诉点击是否在一个用 UI 标签标记的 UI 对象上,所以你可以检查你的屏幕点击函数是否应该触发你的事件

public static class InputHandler
{
    public const string CompareTagForUIElements = "UI";

    public static bool IsPointerOverUIObject(int touchId)
    {
        var eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        // I'm using touch since you are talking about smartphones, 
        // if you still need click use Input.mousePosition
        eventDataCurrentPosition.position = new Vector2(GetTouch(touchId).position.x, GetTouch(touchId).position.y);
        List<RaycastResult> results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
        for (int i = 0; i < results.Count; i++)
        {
            if (results[i].gameObject.CompareTag(CompareTagForUIElements))
                return true;
        }
        return false;
    }
}

所以而不是

public void ITappedOnScreen()
{
    if(Input.GetMouseButtonDown(0))
        Debug.Log("Screen tapped");
}

public void ITappedOnScreen()
{
    if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Begin &&
        !InputHandler.IsPointerOverUIObject(0))
        Debug.Log("Screen tapped");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM