Version: 2022.3
言語: 日本語
WebGL のパフォーマンスに関する考慮事項
WebGL のカーソルロックと全画面モード

WebGL Networking

WebGL でネットワークを利用するには、以下の 2 つの方法があります。

Optionally, you can use WebSockets or WebRTC from JavaScript to implement your own networking. Note that you can’t use .NET networking classes, because JavaScript code doesn’t have direct access to IP Sockets to implement network connectivity.

Use the UnityWebRequest class in WebGL

Unity supports the UnityWebRequest class in WebGL. To implement the UnityWebRequest class, Unity uses the JavaScript Fetch API, which uses the browser to handle web requests. This imposes security restrictions on accessing cross-domain resources.

Unity コンテンツをホストするサーバー以外のサーバーにウェブリクエストを送信する場合は、送信先のサーバーが Unity コンテンツを承認する必要があります。

WebGL でクロスドメインのウェブリソースにアクセスするには、アクセスしようとしているサーバーが オリジン間リソース共有 (CORS) を使用してドメインのウェブリソースを認証する必要があります。

If you try to access content using UnityWebRequest, and the remote server doesn’t have CORS set up or configured correctly, an error like the following appears in the browser console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://myserver.com/. この問題はリソースを同じドメインに移すか、 CORS を使用可能にすると修正されます

サーバーは、送信する http レスポンスに Access-Control ヘッダーを加えて、どのウェブページがウェブブラウザーからその情報を読み取る権限を持っているかを示す必要があります。

Access-Control ヘッダーを加えて、Unity WebGL が任意のオリジンからウェブサーバー上のリソースにアクセスできるようにする方法は、次の例を参照してください。この例では、一般的なリクエストヘッダーを含み、GET、POST、または OPTIONS メソッドを許可しています。

"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers": "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Origin": "*",

UnityWebRequest のダウンロード

Don’t use code that blocks a UnityWebRequest download, such as this:

while(!www.isDone) {}

You can’t block the thread to wait for a UnityWebRequest download to finish otherwise your application freezes. Because WebGL is single threaded, and the fetch API in JavaScript is asynchronous, your download might not finish unless you return control to the browser. Instead, use a Coroutine and a yield statement to wait for the download to finish. For more information, see Examples of coroutines using UnityWebRequest.

Unity Multiplayer の使用

Unity Multiplayer enables communication via the WebSockets protocol. See NetworkServer.useWebSockets.

JavaScript の WebSocket またはWebRTC の使用

WebGL doesn’t allow direct access to IP Sockets, but you can use WebSockets or WebRTC (the two most common networking protocols supported by browsers) to get around this. While WebSockets are widely supported, WebRTC allows peer-to-peer connections between browsers and unreliable connections. Unity doesn’t have a built-in API that allows you to use WebSockets or WebRTC, but you can use a JavaScript plugin to implement this. You can find plugins that implement WebSocket networking on the Unity Asset Store.

WebGL のパフォーマンスに関する考慮事項
WebGL のカーソルロックと全画面モード