3

统一 5.4

构建一个 Unity WebGL 应用程序(不是游戏),在 Unity 方面处理所有 3D 内容,并且所有 UI 都是使用 HTML/CSS/JS 构建的。默认情况下,WebGLInput.captureAllKeyboardInput 设置为 true,这会导致任何需要键盘(文本)输入的输入字段被破坏,因为任何键盘控件都会自动被 Unity 吃掉,而不是进入输入字段。正在做

#if !UNITY_EDITOR && UNITY_WEBGL
WebGLInput.captureAllKeyboardInput = false;
#endif

修复了输入字段的问题,但导致统一忽略所有键盘输入,即使在元素被聚焦之后,但是添加

tabindex="1"

对其进行了修复,以便 HTML 输入字段上的键盘输入在聚焦时可以工作,Unity WebGL 应用程序中的键盘控件在聚焦时也可以工作。(这是所有文档:https ://docs.unity3d.com/ScriptReference/WebGLInput-captureAllKeyboardInput.html )。所以这一切都很好。

但是,Unity WebGL 应用程序仍然会导致某些使用鼠标(而非键盘)控件的输入字段出现问题。也就是说,我在 input type="range" 字段(HTML5 滑块)和 input type="number 上注意到了它(使用键盘输入数字有效,但鼠标上下点击无效)。

有什么解决方法可以解决这个问题吗?我基本上需要防止 Unity WebGL 画布不会自动获取所有鼠标输入,除非首先单击/聚焦元素(就像键盘控件的工作方式一样)。在 Unity 方面有什么需要改变来解决这个问题吗?还是我需要编写一些自定义 JavaScript 来处理所有输入并确定它是用于 Unity 场景还是用于 HTML UI?

4

1 回答 1

5

我遇到了同样的问题,但我相信我找到了解决方法!最初我只是打算使用 OnApplicationFocus 来切换 WebGLInput.captureAllKeyboardInput。但是 OnApplicationFocus 不适用于 Unity 的 WebGL 构建,所以我正在这样做。

在加载游戏时,我在第一个场景中的 GameObject 上有一个名为“GameControl”的脚本,该脚本也名为“GameControl”。

// In the Start function of this script I call a function on the webpage to let it know that the game has loaded.
void Start () {
    #if (UNITY_WEBPLAYER || UNITY_WEBGL) && !UNITY_EDITOR
    try {
        Application.ExternalCall("GameControlReady");
    } catch (System.Exception e) {
        Debug.LogError("GameControlReady function not on webpage"+e);
    }
    #endif
}

// This function will be called from the webpage
public void FocusCanvas (string p_focus) {
    #if !UNITY_EDITOR && UNITY_WEBGL
    if (p_focus == "0") {
        WebGLInput.captureAllKeyboardInput = false;
    } else {
        WebGLInput.captureAllKeyboardInput = true;
    }
    #endif
}

在网页上,我有以下 javascript:

var gameReady = false;

// Called by Unity in GameControl's start function
function GameControlReady () {
    gameReady = true;
}

function FocusCanvas(focus) {
    if (gameReady) {
        SendMessage("GameControl", "FocusCanvas", focus);
    }
}

在网页的头部,我有以下内容

<script type='text/javascript'>
    document.addEventListener('click', function(e) {
        if (e.target.id == "canvas") {
            // Clicked on canvas
            FocusCanvas("1");
        } else {
            // Clicked outside of canvas
            FocusCanvas("0");
        }
    });
</script>
于 2016-10-29T21:13:48.680 回答