Version: 2021.3
言語: 日本語
WebGL の入力
Building and distributing a WebGL project

WebGL のネットワーク

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.

WebGL での UnityWebRequest クラスの使用

Unity は、WebGL でUnityWebRequest クラスをサポートします。UnityWebRequest クラスを実装するために、Unity は JavaScript Fetch API を使用します。この API は、ブラウザーを使ってウェブリクエストを処理します。このため、クロスドメイン (ドメインをまたぐ) のリソースへのアクセスにはセキュリティ上の制約があります。

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 は、WebSockets プロトコルによる通信を可能にします。詳しくは、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 の入力
Building and distributing a WebGL project