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

WebGL のネットワーク

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

任意で、JavaScript の WebSockets または WebRTC を使用して、独自のネットワークを実装することができます。JavaScript のコードはネットワーク接続を実装するための IP ソケットに直接アクセスできないため、.NET のネットワーククラスは使用できないことに注意してください。

WebGL での UnityWebRequest クラスの使用

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

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

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

UnityWebRequest を使用してコンテンツにアクセスしようとするときに、リモートサーバーに CORS が設定されていないと、ブラウザーのコンソールに以下のようなエラーが表示されます。

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 のダウンロード

以下のような、UnityWebRequest のダウンロードをブロックするコードは使用しないでください。

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