Unity WebGL will absorb all keyboard input from your web page. This is actually a great feature as it allows the player to interact with your game without clicking on the game, however, it can be frustrating if you have other elements on your page (such as email sign ups). Luckily, there’s a quick fix.
Stop Capturing All Keyboard Input
#if !UNITY_EDITOR && UNITY_WEBGL WebGLInput.captureAllKeyboardInput = false; #endif
This lets Unity know you don’t need it to capture everything. Now, your emails sign up will work, but your keyboard game inputs may not. To allow the player to use the keyboard as input again, you’ll need to move on to part two.
Start Capturing the Right Keyboard Inputs
Disabling captureAllKeyboardInput means we’re not longer focused on our game by default. In my experience, clicking on the window wasn’t enough to regain focus either. We’ll solve both problems with a quick script.
<script> var recaptureInputAndFocus = function() { var canvas = document.getElementById("#canvas"); if(canvas) { canvas.setAttribute("tabindex", "1"); canvas.focus(); } else setTimeout(recaptureInputAndFocus, 100); } recaptureInputAndFocus(); </script>
The canvas element we’re referencing is created within the Unity script at runtime, so make sure this scripts comes after the Unity script. (Non-async scripts are run in the order they’re found, so just it on the next line.)
First, we set the tabindex, so the player can change the focus on and off the game. Second, we focus on the canvas by default so our players can get straight to playing!
Polishing It Up
Now you may notice an outline around your canvas as the browser highlights the selected element. If you like this effect, you can leave it. Otherwise, add outline: none;
or :focus {outline:none;}
to your css or customize the focus further.
Summary
That’s it! I told you it was easy.
Edit: In a previous version of the javascript, I had an issue with getting the canvas element even after the UnityLoader instantiating in Safari. Now, the code waits 100 milliseconds and tries again if it can’t find the canvas element.
Be First to Comment