Unity WebGL - 阻止<canvas>吃掉所有鼠标/键盘输入? (HTML输入字段)

时间:2016-08-11 13:35:53

标签: html5 unity3d input unity-webgl

Unity 5.4

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

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

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

tabindex="1"

修复它,使得HTML输入字段上的键盘输入在聚焦时起作用,Unity WebGL应用程序内的键盘控件也可以在聚焦时工作。 (这完全符合文档:https://docs.unity3d.com/ScriptReference/WebGLInput-captureAllKeyboardInput.html)。所以这一切都很好。

但是,Unity WebGL应用程序仍然使用MOUSE(非键盘)控件导致某些输入字段出现问题。即我在输入类型=“范围”字段(HTML5滑块)和输入类型=“数字(使用键盘键入数字工作,但鼠标上下单击不工作)时注意到它。

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

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,但我相信我找到了一个解决方法!最初我只是想使用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>