在Unity3D/2D鼠标放外面是不是可以?

In Unity3D/2D Mouse released outside is not possible?

我正在为我的游戏开发 UI。我从简单的播放按钮开始。

当它被触摸时,游戏将开始,但如果用户触摸播放按钮并在播放按钮外释放触摸,则不会发生任何事情。

如何执行这样的操作。我尝试使用以下代码,但 OnMouseUp 中的 else 语句从未执行。

if(Input.GetMouseButtonDown(0)) {

    hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

    if(hit) {

        if(transform.name == hit.transform.gameObject.name) {

            Debug.Log("Button touched");
        }
    }
}else
if(Input.GetMouseButtonUp(0)) {

    //hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

    if(hit)    {

        if(transform.name == hit.transform.gameObject.name) {

            Debug.Log ("touched up over same button.");
        }else {
            Debug.Log ("touched up not over same button.");
        }
    }
}

是否只要触发 MouseDown,该按钮上的 MouseUp 就会始终被触发,除非另一个游戏对象的其他碰撞体未被触及?

在 unity 论坛中有人建议我在此线程上使用 UI 元素 Mouse released outside is not possible?

但是,如果我们想对游戏对象应用相同的行为,那该怎么办?

如果我理解正确,您正在寻找一种方法,不仅可以检测鼠标按钮何时在 GameObject 上释放,还可以检测鼠标按钮何时在 GameObject 以外的任何地方释放。您不必将 Colliders 添加到场景中的所有其他对象即可检测到这一点。

在你的第二个 if 块中,你正在记录光线击中某物并且它击中的东西不是有问题的游戏对象的情况。还有射线什么都没打到的情况:

if(Input.GetMouseButtonUp(0)) {

    hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

    if(hit && transform.name == hit.transform.gameObject.name) {
        Debug.Log ("touched up over same button.");
    } else {
        Debug.Log ("touched up not over same button.");
    }
}