Version: 2021.2
Debugging and troubleshooting WebGL builds
Input in WebGL

Cursor locking and full-screen mode in WebGL

Cursor locking (using Cursor.lockState) and full-screen mode (using Screen.fullScreen) are both supported in Unity WebGLA JavaScript API that renders 2D and 3D graphics in a web browser. The Unity WebGL build option allows Unity to publish content as JavaScript programs which use HTML5 technologies and the WebGL rendering API to run Unity content in a web browser. More info
See in Glossary
, implemented using the respective HTML5 APIs (Element.requestPointerLock and Element.requestFullscreen). These are supported in Firefox and Chrome. Safari cannot currently use full-screen and cursor locking.

Enabling cursor locking and full-screen mode in WebGL

Due to security concerns, browsers will only allow locking the cursor or going into full-screen mode in direct response to a user-initiated event (like a mouse click or key press). Unfortunately, Unity does not have separate event and rendering loops, so it defers event handling to a point where the browser no longer acknowledges a full-screen or cursor lock request issued from Unity scripting as a direct response to the event which triggered it. As a result, Unity triggers the request on the next user-initiated event, rather than the event that triggered the cursor lock or full-scree request.

To make this work with acceptable results, you should trigger cursor locking or full-screen requests on mouse/key down events, instead of mouse/key up events. This ensures that when the request is deferred to the next user-initiated event, it is triggered when the user releases the mouse or key.

Use Unity’s UI.Button component to achieve the desired behaviour by creating a subclass of Button, which overrides the OnPointerDown method.

Note that browsers may show a notification message or ask the user for permission before entering full-screen mode or locking the cursor.

Debugging and troubleshooting WebGL builds
Input in WebGL
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961