c# - Unity IsPointerOverGameObject 问题

标签 c# unity3d

我知道这是一个常见问题,但没有一个有效。可能按键设置不对。我有一个没有图像的面板,在左上角的设置按钮内,单击后会打开另一个场景。我尝试使用这 3 种方法,但都不起作用。它始终将其检测为游戏对象。

bool isGameStarted 正在检查玩家是否应该移动。 请指导我完成

尝试过

if (Swipe.Instance.Tap && !isGameStarted)
{
    if (EventSystem.current.IsPointerOverGameObject() )
    { 
        isGameStarted = false;
    }
    else
    {
          isGameStarted = true;
          motor.StartRunning();
          gameCanvas.SetTrigger("Show");
    }
}

也尝试过使用触发器,但它通过 UI。

这是原始代码。

if (Swipe.Instance.Tap && !isGameStarted)
{ 
    isGameStarted = true;
    motor.StartRunning();
    gameCanvas.SetTrigger("Show");
}

点击屏幕后,播放器开始移动。如果单击设置按钮,我不需要它移动或启动游戏。

最佳答案

我遇到了同样的问题,直到我发现 IsPointerOverGameObject 似乎对任何游戏对象(可能带有碰撞器)而不仅仅是 UI 对象返回 true。

所以我编写了一个自定义静态类来仅检查 UI 对象。您需要将每个面板、图像、按钮等的图层设置为 UI 才能正常工作。

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public static class MouseOverUILayerObject
{
    public static bool IsPointerOverUIObject()
    {
        PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        List<RaycastResult> results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(eventDataCurrentPosition, results);

        for (int i = 0; i < results.Count; i++)
        {
            if (results[i].gameObject.layer == 5) //5 = UI layer
            {
                return true;
            }
        }

        return false;
    }
}

像这样使用它:

private void OnMouseDown()
{
      if (!MouseOverUILayerObject.IsPointerOverUIObject())
            HandleClick();
}

关于c# - Unity IsPointerOverGameObject 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57010713/

相关文章:

c# - 在运行时创建复杂的用户控件而不卡住 GUI

android - 是什么阻止了 Android 用户到达 s3?

c# - 无法让我的相机正确限制其旋转

c# - XML 序列化类结果为空 XML

c# - 使用 HTTPS "The authentication or decryption has failed"的 WebClient.DownloadString

ios - 在 iOS 上使用 C# 的 LINQ OrderBy 的 JIT 错误

c# - 使用 Entity Framework 是否有更简洁或优雅的方法将多个参数传递给 SQL 存储过程?

c# - 为什么我的 Visual Studio T4 代码输出错误?

c# - 无法加载文件或程序集 System.Threading.Tasks,版本 = 2.5.19.0

c# - 在 c# 中某个单词之后/之前从字符串中过滤值