Open18

Unity2021WebGL調査

イワケンイワケン

Introducing WebGL

The WebGL option in the Unity Editor allows you to publish content as JavaScript programs which use HTML5/JavaScript, WebAssembly, WebGL rendering API, and other web standards to run Unity content in a web browser.

Unity EditorのWebGLオプションは、HTML5/JavaScript、WebAssembly、WebGLレンダリングAPIなどのWeb標準を利用し、Webブラウザ上でUnityコンテンツを実行するJavaScriptプログラムとしてコンテンツを公開することができるものです。

ページ 説明
WebGL Browser Compatibility A list of the supported browsers for WebGL.
WebGL Graphics How to use the WebGL Graphics API.
Using Audio in WebGL Information about audio capabilities in WebGL.
Embedded Resources on WebGL Information about embedded resources in WebGL.
イワケンイワケン

https://docs.unity3d.com/ja/2021.3/Manual/webgl-browsercompatibility.html

WebGL browser compatibility

Unity WebGL support for desktop browsers differs depending on the browser. It supports browsers where all of the following are true:

Unity WebGL のデスクトップ・ブラウザーへの対応は、ブラウザーによって異なります。以下のいずれにも該当するブラウザをサポートしています。

  • The browser is WebGL 1 or WebGL 2 capable. Note: Unity has marked WebGL 1 support for deprecation and will remove it in a future release.
    • ブラウザは、WebGL 1 または WebGL 2 に対応しています。注意:Unity は WebGL 1 サポートを非推奨とし、将来のリリースで削除する予定です。
  • The browser is HTML 5 standards-compliant.
    • HTML5規格に準拠したブラウザです。
  • The browser is 64-bit and supports WebAssembly.
    • ブラウザは64ビットで、WebAssemblyをサポートしています。

Unity WebGL doesn’t support mobile devices. It might work on high-end devices, but current devices are often not powerful enough and don’t have enough memory to support Unity WebGL content. To make the end user aware of this, the default template for Unity WebGL displays a warning message when the end user attempts to load a Unity WebGL application on a mobile browser. To remove this warning from your application, add your own WebGL template. For information on how to do this, see Add a WebGL template.

Unity WebGLはモバイルデバイスをサポートしていません 。ハイエンドのデバイスでは動作するかもしれませんが、現在のデバイスはUnity WebGLのコンテンツをサポートするのに十分な性能とメモリを持っていないことが多いのです。このことをエンドユーザーに認識してもらうために、Unity WebGL のデフォルトテンプレートでは、エンドユーザーがモバイルブラウザで Unity WebGL アプリケーションをロードしようとすると、警告メッセージが表示されるようになっています。アプリケーションからこの警告を取り除くには、独自の WebGL テンプレートを追加します。この方法については、WebGL テンプレートの追加を参照してください。

Unity WebGL supports some compressed texture formats. For information on the compressed texture formats Unity WebGL supports, see Recommended, default, and supported texture compression formats, by platform.

Unity WebGL はいくつかの圧縮テクスチャ形式をサポートしています。Unity WebGL がサポートする圧縮テクスチャフォーマットについては、プラットフォーム別の推奨、デフォルト、およびサポートされるテクスチャ圧縮フォーマットを参照してください。

Desktop Browser Desktop Platforms
Google Chrome Windows, macOS, Linux
Mozilla Firefox Windows, macOS, Linux
Apple Safari macOS
Microsoft Edge Windows, macOS, Linux

ノート

  • Apple Safari doesn’t support WebGL 2 in versions before Safari 15.
    • Apple Safariは、Safari 15より前のバージョンではWebGL 2をサポートしていません。
  • Apple Safari doesn’t support IndexedDB for content running in an iFrame.
    • Apple Safariは、iFrameで動作するコンテンツ用のIndexedDBをサポートしていません。
  • Only Mozilla Firefox supports the Large-Allocation HTTP header. For information about the Large-Allocation HTTP header, see Memory in WebGL.
    • Mozilla Firefox のみ、Large-Allocation HTTP ヘッダーをサポートしています。
    • Large-Allocation HTTP ヘッダーの詳細については、「WebGL のメモリ」を参照してください。
  • Unity WebGL no longer supports Microsoft Edge Legacy. Unity WebGL supports the new Microsoft Edge based on Chromium.
    • Unity WebGLは、Microsoft Edge Legacyをサポートしなくなりました。Unity WebGL は Chromium ベースの新しい Microsoft Edge をサポートします。

WebGL 1 deprecation

In version 2021.2, Unity marked support for the WebGL 1 Graphics API as deprecated. Currently, there are no changes in behavior and Unity still includes the WebGL 1 Graphics API if you enable the Auto Graphics API Player Setting. However, Unity will remove support for WebGL 1 In a future release.
バージョン 2021.2 で、Unity は WebGL 1 Graphics API のサポートを非推奨としました。現在のところ、動作に変更はなく、プレイヤー設定のAuto Graphics APIを有効にすると、UnityはWebGL 1 Graphics APIを搭載しています。しかし、Unity は将来のリリースで WebGL 1 のサポートを終了する予定です。

WebGL 1 graphics card blocklists

GPU blocklists apply. Older graphics cards might not support WebGL. For more information, see:
GPUブロックリストが適用されます。古いグラフィックカードはWebGLをサポートしていない場合があります。詳細はこちらをご覧ください。

イワケンイワケン

https://docs.unity3d.com/ja/2021.3/Manual/webgl-graphics.html

WebGL Graphics

WebGL はウェブブラウザーでグラフィックスをレンダリングするための API で、OpenGL ES グラフィックスライブラリの機能にもとづいています。WebGL 1.0 は OpenGL ES 2.0 の機能とほぼ一致し、WebGL 2.0 は OpenGL ES 3.0 の機能とほぼ一致します。

カメラのクリア

WebGL のデフォルトの動作は、フレームごとに描画バッファをクリアします。つまり、Unity WebGL では Camera.clearFlags 設定に関係なく、フレームバッファの内容はクリアされます。ただし、この動作はインスタンス化のときに変更できます。変更するには、WebGL テンプレートで webglContextAttributes.preserveDrawingBuffer を true に設定します。

script.onload = () => {
       config['webglContextAttributes'] = {"preserveDrawingBuffer": true}; // Add this line to the index.html file in a WebGL Template
       createUnityInstance(canvas, config, (progress) => }

ディファードレンダリング

WebGL2.0 が使用可能な場合、Unity WebGL は ディファードレンダリングパス のみをサポートします。WebGL1.0 では、Unity WebGL ランタイムは フォワードレンダリング にフォールバックします。

グローバルイルミネーション

Unity WebGL only supports baked GI. Enlighten Realtime Global Illumination is not currently supported in WebGL. Furthermore, only Non-Directional lightmaps are supported.
Unity WebGLはベイクドGIのみをサポートしています。 Enlighten Realtime Global Illuminationは、現在WebGLではサポートされていません。さらに、Non-Directional lightmapのみサポートされています。

リニアレンダリング

Unity WebGL は WebGL 2.0 で リニア色空間レンダリング のみをサポートします。リニア色空間レンダリングで WebGL 1.0 のフォールバックサポートはありません。リニア色空間レンダリングを使用して WebGL プレイヤーをビルドするには、Player 設定で WebGL 1.0 API を削除し、Other Settings パネルを開き、Automatic Graphics API 設定を無効にします。

一部のウェブブラウザーは sRGB DXT テクスチャ圧縮 をサポートしていません。これにより、すべての DXT テクスチャをランタイムに解凍するため、リニアレンダリングを使用するときにレンダリングパフォーマンスの品質が低下します。

Video Clip Importer

On the WebGL platform, video clips aren’t imported to the Unity project using VideoClipImporter, as it would increase initial asset data download sizes and prevent network streaming. For video playback, use the URL option in the VideoPlayer component and place the asset in the StreamingAssets/ directory to use the built-in network streaming of your browser.

WebGL プラットフォームでは、VideoClipImporter を使用して動画クリップを Unity プロジェクトにインポートしません。これは、初期のアセットデータのダウンロードサイズが増加し、ネットワークストリーミングができなくなるためです。動画再生には VideoPlayer コンポーネントの URL オプションを使用し、アセットを StreamingAssets/ ディレクトリに配置して、ブラウザの組み込みネットワーク ストリーミングを使用します。

WebGL シェーダーコードの制限

WebGL 1.0 仕様 は GLSLS シェーダーコードにいくつかの制限を課しています。これらの制限は多くの OpenGL ES 2.0 実装よりもより厳しいものです。これは多くの場合、独自のシェーダーを作成する場合に関わってきます。

特に WebGL には配列や行列のインデックス化に使用できる値に関して制限があります。具体的には、WebGL が動的インデックスを使用可能なのは、定数式、ループインデックス、または、それらの組み合わせのみです。頂点シェーダーの Uniform アクセスだけは例外で、どんな式を用いてもインデックスを使えます。

管理構造にも制限が課されます。使用できるループのタイプは、数えるための for ループのみです。このループでは、イニシャライザーが変数を初期化して定数にしたり、更新によって定数を変数に加算/変数から定数を減算したり、継続テストで変数を定数と比較することなどを行います。この条件と合致しない for ループと while ループは使用できません。

フォントレンダリング

Unity WebGL は他すべての Unity プラットフォームのようにダイナミックフォントレンダリングをサポートしています。ただし、ユーザーのマシンにインストールされているフォントにアクセスすることはできないため、使用されるすべてのフォントは (多言語フォントに対応するフォントや、太字やイタリックのフォントの代替フォントも含めて) プロジェクトフォルダーに置き、代替として使うため、Font Names にリストする 必要があります。

アンチエイリアス

WebGL は、ブラウザーと GPU のほとんどすべて (ただし、すべてではない) の組み合わせでアンチエイリアスをサポートします。これを使用するには、WebGL プラットフォームのデフォルトの Quality 設定でアンチエイリアスを有効にする必要があります。

WebGL1.0 にはいくつかの制限があることに注意してください。

ランタイムに Quality 設定を切り替えることで、アンチエイリアスを有効または無効にすることはできません。プレイヤーの起動時にロードするデフォルトの Quality 設定であることが必要です。

異なるマルチサンプリングレベル (2x、4x など) は WebGL では効力がありません。オンとオフのどちらかです。

カメラに適用された ポストプロセスエフェクト は、ビルトインのアンチエイリアスを無効にします。

HDR はアンチエイリアスには対応していません。そのため、Allow HDR カメラオプションを無効にしてください。

WebGL2.0 にはこのような制限はありません。

リフレクションプローブ

リフレクションプローブは WebGL でサポートされています。しかし、特定のミップマップへのレンダリングに関する WebGL 仕様の制限により、滑らかなリアルタイムのリフレクションプローブはサポートされません (そのため、リアルタイムのリフレクションプローブは常に鋭いリフレクションを生成し、とても解像度が低く見えます)。滑らかなリアルタイムのリフレクションプローブには WebGL 2.0 が必要です。

WebGL 2.0 のサポート

Unity には WebGL 2.0 API のサポートが含まれており、ウェブに対する OpenGL ES 3.0 レベルのレンダリング機能を提供します。

デフォルトでは、Unity WebGL ビルドは WebGL 1.0 と WebGL 2.0 API の両方をサポートしています。これは Other Settings パネルの WebGL Player 設定で Automatic Graphics API プロパティを無効にすることによって設定します。

WebGL 2.0 がブラウザーでサポートされている場合、コンテンツは以下のような利点を得られます。スタンダードシェーダーの品質向上、GPU インスタンス のサポート、指向性ライトマップのサポート、シェーダーコードのインデックスやループの制限がないこと、パフォーマンスの向上。

ランタイムに SystemInfo.graphicsDeviceType を使用すると、Unity インスタンスが OpenGLES3 (WebGL2.0) と OpenGLES2 (WebGL1.0)、どちらでレンダリングしているかを判断できます。

イワケンイワケン

https://docs.unity3d.com/ja/2021.3/Manual/webgl-audio.html

Audio in WebGL

This page only provides information about audio capabilities in WebGL. To learn how to use audio in your Unity project, see the Audio Overview.

Because Unity uses FMOD to manage audio for platforms, Unity WebGL supports limited audio functionality, which only includes the basic features. FMOD relies on threads, which WebGL doesn’t support. For this reason, Unity uses an implementation based on the internal Web Audio API, which enables the browser to handle audio playback and mixing.

Note: Google Chrome’s new Autoplay policy prevents autoplay of audio and video under certain conditions. For example, while your game might be set to autoplay some background music soon after the game loads, it won’t play automatically unless you click or tap on the website. For more information on how to enable or disable this policy, see Google Chrome’s documentation on Autoplay policy in Chrome.

このページでは、WebGLのオーディオ機能に関する情報のみを提供しています。Unity プロジェクトでオーディオを使用する方法については、「オーディオの概要」を参照してください。

Unity は FMOD を使用してプラットフォームのオーディオを管理しているため、Unity WebGL は基本的な機能のみを含む限られたオーディオ機能をサポートしています。FMOD はスレッドに依存しており、WebGL はこれをサポートしていません。このため、Unity では内部の Web Audio API に基づく実装を使用し、ブラウザでオーディオの再生とミキシングを処理できるようにしています。

注意:Google Chrome の新しい Autoplay ポリシーでは、特定の条件下で音声と動画の自動再生を防止しています。たとえば、ゲームがロードされた直後にいくつかの BGM が自動再生されるように設定されていても、ウェブサイトをクリックまたはタップしない限り、自動再生されることはありません。このポリシーを有効または無効にする方法について詳しくは、Google Chrome のドキュメント「Chrome の自動再生ポリシー」を参照してください。

Audio Playback and Browser Security

For security reasons, browsers don’t allow audio playback until an end user interacts with your application webpage via a mouse click, touch event or key press. Use a loading screen to allow the end user to interact with your application and start audio playback before your main content begins.

セキュリティ上の理由から、ブラウザは、エンドユーザーがマウスクリック、タッチイベント、またはキープレスによってアプリケーションのウェブページと対話するまで、オーディオの再生を許可しません。ローディングスクリーンを使って、エンドユーザーがアプリケーションと対話できるようにし、メインコンテンツが始まる前にオーディオ再生を開始するようにします。

イワケンイワケン

Embedded Resources on WebGL

.NET assemblies can contain embedded resources. An embedded resource is a collection of binary data that is part of the .NET assembly. You can access this binary data in code via a file-like API.

By default, WebGL builds don’t include embedded resources. This helps to keep the size of the final binary lower, because embedded resources can be rather large. However, some user code and .NET class library APIs depend on the presence of embedded resources to work properly. For example, string comparisons that use the StringComparison.InvariantCultureIgnoreCase value use embedded resources when comparing non-ASCII characters.

You can use the following Editor script to enable embedded resources for a WebGL build:

.NETアセンブリには、埋め込みリソースを含めることができます。埋め込みリソースは、.NETアセンブリの一部であるバイナリデータのコレクションです。このバイナリ データには、ファイルのような API を介してコードでアクセスできます。

デフォルトでは、WebGL のビルドには埋め込みリソースが含まれません。埋め込みリソースはかなり大きくなる可能性があるため、これは最終的なバイナリのサイズを低く保つのに役立ちます。しかし、ユーザーコードと.NETクラスライブラリAPIの中には、適切に動作するために埋め込みリソースの存在に依存するものがあります。たとえば、StringComparison.InvariantCultureIgnoreCase値を使用する文字列比較は、非ASCII文字を比較するときに埋め込みリソースを使用します。

次のエディタースクリプトを使用すると、WebGL ビルドの埋め込みリソースを有効にすることができます。

using UnityEditor;

public class WebGLEditorScript
{
    [MenuItem("WebGL/Enable Embedded Resources")]
    public static void EnableEmbeddedResources()
    {
        PlayerSettings.WebGL.useEmbeddedResources = true ("useEmbeddedResources", true, BuildTargetGroup.WebGL);
    }
}

When this Player setting is enabled, the WebGL build includes any embedded resources in any .NET assemblies the Project uses.

このPlayer設定を有効にすると、WebGLビルドには、プロジェクトが使用するすべての.NETアセンブリにある埋め込みリソースが含まれます。

イワケンイワケン

Getting started with WebGL development

This page describes what you need to do before building a WebGL app. To build a WebGL application, you must first install the Unity Hub and then add the WebGL Build Support module.
このページでは、WebGLアプリをビルドする前に必要なことを説明します。WebGLアプリをビルドするには、まずUnity Hubをインストールし、WebGL Build Supportモジュールを追加する必要があります。

イワケンイワケン

https://docs.unity3d.com/ja/2021.3/Manual/webgl-technical-overview.html

Advanced overview

This section provides an overview of the platform support and other useful technical information required to build your app using WebGL.

このセクションでは、WebGL を使用したアプリを構築するために必要なプラットフォームのサポートとその他の有用な技術情報の概要を説明します。

Technical Overview

Unity uses the emscripten compiler toolchain to cross-compile the Unity runtime code (written in C and C++) into WebAssembly (also known as Wasm). The main advantages of emscripten it’s designed to be small in size, load-time and memory efficient, and aims to deliver close to native speed execution. For more information about WebAssembly in Unity, check this blog post.

To convert the .NET game code (your C# scripts) into WebAssembly, Unity uses a technology called IL2CPP. IL2CPP takes .NET bytecode and converts it to corresponding C++ source files, which is then compiled using emscripten to convert your scripts to Wasm.

Unityはemscriptenコンパイラツールチェーンを使用して、Unityランタイムコード(CおよびC++で記述)をWebAssembly(Wasmとしても知られています)にクロスコンパイルしています。emscripten の主な利点は、サイズが小さく、ロード時間およびメモリ効率が高く、ネイティブ速度に近い実行を実現することを目的として設計されていることです。Unity での WebAssembly の詳細については、こちらのブログ記事をご覧ください。

.NETゲームコード(C#スクリプト)をWebAssemblyに変換するために、UnityはIL2CPPと呼ばれる技術を使用します。IL2CPP は .NET バイトコードを受け取り、対応する C++ ソースファイルに変換し、それを emscripten を使用してコンパイルしてスクリプトを Wasm に変換します。

Platform support

Most popular desktop browser versions support the Unity WebGL content, but do note that different browsers offer different level of support. For example, Unity WebGL doesn’t support Mobile devices.

The following features in WebGL builds are either not available or limited due to constraints of the platform itself:

ほとんどのデスクトップ用ブラウザは、Unity WebGL のコンテンツをサポートしていますが、ブラウザによってサポートレベルが異なることに注意してください。例えば、Unity WebGL はモバイルデバイスをサポートしていません。

WebGL ビルドの以下の機能は、プラットフォーム自体の制約により、利用できないか制限されています。

  • Threads are not supported due to the lack of threading support in JavaScript. This applies to both Unity’s internal use of threads to speed up performance, and to the use of threads in script code and managed dlls. Essentially, anything in the System.Threading namespace is not supported.
    • System.Threadingのサポートゼロ
  • Debugging of WebGL builds in Visual Studio. See: Debugging and trouble shooting WebGL builds.
    • Visual Studioでデバッグできるよ。詳しくはこちら
  • Browsers don’t allow direct access to IP sockets for networking due to security concerns. See: WebGL Networking.
    • ネットワーク用のIPソケットに直接アクセスすることを許可していません。
  • Limitations with the WebGL graphics API, which is based on the functionality of the OpenGL ES graphics library. See: WebGL Graphics.
    • OpenGL ESグラフィックスライブラリの機能をベースとしたWebGLグラフィックスAPIでの制限事項があります。
  • WebGL builds use a custom backend for Audio, based on the Web Audio API but only supports the basic audio functionality. See: Using Audio in WebGL.
    • WebGL ビルドでは、Web Audio API をベースにしたオーディオ用のカスタム バックエンドを使用しますが、基本的なオーディオ機能のみをサポートします。
  • WebGL is an AOT platform, so it doesn’t allow dynamic generation of code using System.Reflection.Emit. This is the same on all other IL2CPP platforms, iOS, and most
    • WebGLはAOTプラットフォームなので、System.Reflection.Emitを使ったコードの動的生成はできません。これは、他のすべてのIL2CPPプラットフォーム、iOS、およびほとんどのコンソールで同じです。
イワケンイワケン

https://docs.unity3d.com/ja/2021.3/Manual/webgl-deploying.html

Compressed builds and server configuration 圧縮ビルドとサーバー構成

To deploy a WebGL build, you must configure your server and make sure you’re using the correct response headers, so that the browser can receive the proper response and process the response correctly.

There are two main settings in Unity that affect how you set up the server:

  • Compression Format: Determines how Unity compresses files during the build step.
  • Decompression Fallback: Determines how Unity processes downloaded files when the build runs in the browser.

WebGL ビルドを配布するには、サーバーを設定し、正しいレスポンス ヘッダーを使用していることを確認し、ブラウザが適切なレスポンスを受信してそのレスポンスを正しく処理できるようにする必要があります。

Unity には、サーバーの設定方法に影響を与える 2 つの主な設定があります。

  • Compression Format(圧縮形式)。圧縮形式:ビルドステップ中にUnityがファイルを圧縮する方法を決定します。
  • 解凍フォールバック(Decompression Fallback)。ビルドがブラウザで実行されたときに、Unityがダウンロードしたファイルをどのように処理するかを決定します。

Compression Format 圧縮形式

Choose the compression type from the WebGL Player Settings window (menu: Edit > Project Settings > Player, then select WebGL and expand the Publishing Settings section):

圧縮方法

  • gzip
    • This is the default option. Gzip files are bigger than Brotli files, but faster to build, and natively supported by all browsers over both HTTP and HTTPS.
    • これはデフォルトのオプションです。Gzip ファイルは Brotli ファイルより大きいですが、ビルドが速く、HTTP と HTTPS の両方ですべてのブラウザにネイティブにサポートされています。
  • Brotli
    • Brotli compression offers the best compression ratios. Brotli compressed files are smaller than gzip, but take a longer time to compress, which increases your iteration times on release builds. Chrome and Firefox only natively support Brotli compression over HTTPS.
    • Brotli圧縮は、最高の圧縮率を提供します。Brotli圧縮されたファイルはgzipよりも小さいですが、圧縮に時間がかかるため、リリースビルドのイテレーション時間が長くなります。ChromeとFirefoxは、HTTPSでのBrotli圧縮のみをネイティブでサポートしています。
  • Disable
    • Disables compression. Use this option if you want to implement your own compression in post-processing scripts. You should also use it if you plan to use static compression on the hosting server.
    • 圧縮を無効にします。後処理スクリプトで独自の圧縮を実装したい場合は、このオプションを使用します。また、ホスティングサーバーで静的圧縮を使用する予定がある場合も、このオプションを使用する必要があります。

Web server configuration

You might need to adjust your server configuration to match your specific build setup. In particular, there might be issues if you already have another server-side configuration to compress hosted files, which could interfere with this setup. To make the browser perform decompression natively while it downloads your application, append a Content-Encoding header to the server response. This header must correspond to the type of compression Unity uses at build time. For code samples, see Server Configuration Code Samples.
あなたの特定のビルド設定に合うように、サーバーの設定を調整する必要があるかもしれません。特に、ホストされたファイルを圧縮する別のサーバーサイドの設定をすでに行っている場合は、 この設定と干渉する可能性があり、問題が発生する可能性があります。アプリケーションのダウンロード中にブラウザがネイティブに解凍を行うようにするには、サーバーのレスポンスに Content-Encoding ヘッダを追加します。このヘッダは、Unityがビルド時に使用する圧縮の種類に対応している必要があります。コードサンプルについては、「サーバー設定コードサンプル」を参照してください。

Decompression fallback

The decompression fallback option enables Unity to automatically embed a JavaScript decompressor into your build. This decompressor corresponds to your selected compression method, and decompresses your content if the browser fails to do so.

decompression fallback オプションを使用すると、Unity は自動的に JavaScript decompressor をビルドに埋め込むことができます。この解凍器は、選択した圧縮方法に対応し、ブラウザが圧縮に失敗した場合にコンテンツを解凍します。

Enabling decompression fallback

Enable decompression fallback from the Player Settings window (menu: Edit > Project Settings > Player, then select WebGL and expand the Publishing Settings section).

When you enable decompression fallback, Unity adds a .unityweb extension to the build files. You should consider using Decompression Fallback if you have less experience with server configuration, or if server configuration is unavailable to you.

Note: Using this option results in a larger loader size and a less efficient loading scheme for the build files.

プレーヤー設定ウィンドウから解凍フォールバックを有効にする(メニュー。Edit > Project Settings > Player、そしてWebGLを選択し、Publishing Settingsセクションを展開します)。

Decompression Fallback を有効にすると、Unity はビルド ファイルに .unityweb 拡張子を追加します。サーバー設定の経験が少ない場合、またはサーバー設定が利用できない場合は、Decompression Fallbackの使用を検討する必要があります。

注意:このオプションを使用すると、ローダーサイズが大きくなり、ビルドファイルの読み込みスキームが効率的でなくなります。

Disabling decompression fallback

The Decompression Fallback option is disabled by default. Therefore, by default, build files have an extension that corresponds to the compression method you select.

There are two compression methods to choose from: gzip or Brotli. For further information see the compression format section.

To enable browsers to natively decompress Unity build files while they’re downloading, you need to configure your web server to serve the compressed files with the appropriate HTTP headers. This is called native browser decompression. It has the advantage of being faster than the JavaScript decompression fallback, which can reduce your application’s startup time.

The setup process for native browser decompression depends on your web server. For code samples, see Server Configuration Code Samples.

Decompression Fallbackオプションは、デフォルトで無効になっています。したがって、デフォルトでは、ビルドファイルは、選択した圧縮方法に対応する拡張子を持ちます。

圧縮方式は、gzipとBrotliの2種類から選択できます。詳細については、圧縮形式のセクションを参照してください。

Unity ビルドファイルのダウンロード中にブラウザがネイティブに解凍できるようにするには、適切な HTTP ヘッダーを付けて圧縮ファイルを提供するように Web サーバーを設定する必要があります。これはネイティブブラウザ解凍と呼ばれます。これは、JavaScriptの解凍フォールバックよりも高速であるという利点があり、アプリケーションの起動時間を短縮することができます。

ネイティブブラウザー解凍の設定プロセスは、使用するWebサーバーによって異なります。コードサンプルについては、「サーバー設定コードサンプル」を参照してください。

Content-Encoding headers

A Content-Encoding header tells the browser which type of compression Unity has used for the compressed files. This allows the browser to decompress the files natively.

Set the Content-Encoding response header to the compression method selected in the Player Settings.

Content-Encodingヘッダーは、Unityが圧縮ファイルに使用した圧縮の種類をブラウザに知らせます。これにより、ブラウザはファイルをネイティブに解凍することができます。

Content-Encoding レスポンスヘッダを、プレイヤー設定で選択した圧縮方式に設定します。

  • gzip
    • .gz
    • Content-Encoding: gzip
  • Brotli
    • .br
    • Content-Encoding: br

WebAssembly streaming (higher level header)

WebAssembly streaming allows the browser to compile the WebAssembly code while it is still downloading the code. This significantly improves loading times.

For WebAssembly streaming compilation to work, the server needs to return WebAssembly files with an application/wasm MIME type. To use WebAssembly streaming, you need to serve WebAssembly files with the Content-Type: application/wasm response header. A Content-Type header tells the server which media type the content is. This value should be set to application/wasm for WebAssembly files.

WebAssemblyストリーミングにより、ブラウザはWebAssemblyコードをダウンロードしたままコンパイルすることができます。これにより、ロード時間が大幅に改善されます。

WebAssembly ストリーミング コンパイルが機能するためには、サーバーは WebAssembly ファイルを application/wasm という MIME タイプで返す必要があります。WebAssemblyストリーミングを使用するには、Content-Type: application/wasm 応答ヘッダーを持つ WebAssembly ファイルを提供する必要があります。Content-Type ヘッダーは、コンテンツがどのメディアタイプであるかをサーバーに知らせます。この値は、WebAssembly ファイルに対して application/wasm に設定する必要があります。

  • .wasm, .wasm.gz, .wasm.br
    • Content-Type: application/wasm

Note: WebAssembly streaming does not work together with JavaScript decompression (when the Decompression Fallback option is enabled). In such cases, the downloaded WebAssembly file must first go through the JavaScript decompressor and therefore the browser cannot stream it during download.

注意: WebAssembly ストリーミングは、JavaScript の解凍と一緒に動作しません (Decompression Fallback オプションが有効な場合)。この場合、ダウンロードされた WebAssembly ファイルは最初に JavaScript の解凍を通過する必要があるため、ブラウザはダウンロード中にそれをストリーミングできません。

Additional headers

If your file contains JavaScript, you should add the application/javascript Content-Type header. Some servers might include this automatically, while others do not.

ファイルにJavaScriptが含まれている場合、application/javascript Content-Typeヘッダを追加する必要があります。サーバーによっては、これを自動的に含める場合と含めない場合があります。

  • .js, .js.gz, js.br
    • Content-Type: application/javascript
イワケンイワケン

https://docs.unity3d.com/ja/2021.3/Manual/webgl-server-configuration-code-samples.html

Server configuration code samples

以下のコードサンプルは、WebGL を使用する際のサーバーの設定方法について説明しています。以下のサンプルは、Nginx、Apache、および IIS サーバーに適用されます。WebGL のサーバー設定については、WebGL: Compressed Builds and server configuration を参照してください。

http {
# ...

server {
# Add the following config within http server configuration
# ...
 
# On-disk Brotli-precompressed data files should be served with compression enabled:
location ~ .+\.(data|symbols\.json)\.br$ {
    # Because this file is already pre-compressed on disk, disable the on-demand compression on it.
    # Otherwise nginx would attempt double compression.
    gzip off;
    add_header Content-Encoding br;
    default_type application/octet-stream;
}

# On-disk Brotli-precompressed JavaScript code files:
location ~ .+\.js\.br$ {
    gzip off; # Do not attempt dynamic gzip compression on an already compressed file
    add_header Content-Encoding br;
    default_type application/javascript;
}

# On-disk Brotli-precompressed WebAssembly files:
location ~ .+\.wasm\.br$ {
    gzip off; # Do not attempt dynamic gzip compression on an already compressed file
    add_header Content-Encoding br;
    # Enable streaming WebAssembly compilation by specifying the correct MIME type for
    # Wasm files.
    default_type application/wasm;
}

# On-disk gzip-precompressed data files should be served with compression enabled:
location ~ .+\.(data|symbols\.json)\.gz$ {
    gzip off; # Do not attempt dynamic gzip compression on an already compressed file
    add_header Content-Encoding gzip;
    default_type application/octet-stream;
}

# On-disk gzip-precompressed JavaScript code files:
location ~ .+\.js\.gz$ {
    gzip off; # Do not attempt dynamic gzip compression on an already compressed file
    add_header Content-Encoding gzip;
    default_type application/javascript;
}

# On-disk gzip-precompressed WebAssembly files:
location ~ .+\.wasm\.gz$ {
    gzip off; # Do not attempt dynamic gzip compression on an already compressed file
    add_header Content-Encoding gzip;
    # Enable streaming WebAssembly compilation by specifying the correct MIME type for
    # Wasm files.
    default_type application/wasm;
}
}
}

Server configuration for WebGL builds (Apache)

# This configuration file should be uploaded to the server as "<Application Folder>/Build/.htaccess"
# NOTE: "mod_mime" Apache module must be enabled for this configuration to work.
<IfModule mod_mime.c>

# The following lines are required for builds without decompression fallback, compressed with gzip
RemoveType .gz
AddEncoding gzip .gz
AddType application/octet-stream .data.gz
AddType application/wasm .wasm.gz
AddType application/javascript .js.gz
AddType application/octet-stream .symbols.json.gz

# The following lines are required for builds without decompression fallback, compressed with Brotli
RemoveType .br
RemoveLanguage .br
AddEncoding br .br
AddType application/octet-stream .data.br
AddType application/wasm .wasm.br
AddType application/javascript .js.br
AddType application/octet-stream .symbols.json.br

# The following line improves loading performance for uncompressed builds
AddType application/wasm .wasm

# Uncomment the following line to improve loading performance for gzip-compressed builds with decompression fallback
# AddEncoding gzip .unityweb

# Uncomment the following line to improve loading performance for brotli-compressed builds with decompression fallback
# AddEncoding br .unityweb

</IfModule>

Server configuration for compressed WebGL builds without decompression fallback (IIS)

lls
<?xml version="1.0" encoding="UTF-8"?>
<!--
 The following server configuration can be used for compressed WebGL builds without decompression fallback.
 This configuration file should be uploaded to the server as "<Application Folder>/Build/web.config".

NOTE: To host compressed WebGL builds without decompression fallback, you need to install the "URL Rewrite" IIS module on the server.
Otherwise, IIS will throw an exception when using this configuration file.
This module is available at https://www.iis.net/downloads/microsoft/url-rewrite.
-->


<configuration>
 <system.webServer>
   <!--
     Compressed Unity builds without decompression fallback can't be properly hosted on a server which
     has static compression enabled because this might result in the build files being compressed twice.
     The following line disables static server compression.
   -->
   <urlCompression doStaticCompression="false" />
   <!-- To host compressed Unity builds, the correct mimeType should be set for the compressed build files. -->
   <staticContent>
     <!--
       NOTE: IIS will throw an exception if a mimeType is specified multiple times for the same extension.
       To avoid possible conflicts with configurations that are already on the server, you should remove the mimeType for the corresponding extension using the <remove> element,
       before adding mimeType using the <mimeMap> element.
     -->
     <!-- The following lines are required for builds compressed with gzip, which don't include decompression fallback. -->
     <remove fileExtension=".data.gz" />
     <mimeMap fileExtension=".data.gz" mimeType="application/octet-stream" />
     <remove fileExtension=".wasm.gz" />
     <mimeMap fileExtension=".wasm.gz" mimeType="application/wasm" />
     <remove fileExtension=".js.gz" />
     <mimeMap fileExtension=".js.gz" mimeType="application/javascript" />
     <remove fileExtension=".symbols.json.gz" />
     <mimeMap fileExtension=".symbols.json.gz" mimeType="application/octet-stream" />
     <!-- The following lines are required for builds compressed with Brotli, which don't include decompression fallback. -->
     <remove fileExtension=".data.br" />
     <mimeMap fileExtension=".data.br" mimeType="application/octet-stream" />
     <remove fileExtension=".wasm.br" />
     <mimeMap fileExtension=".wasm.br" mimeType="application/wasm" />
     <remove fileExtension=".js.br" />
     <mimeMap fileExtension=".js.br" mimeType="application/javascript" />
     <remove fileExtension=".symbols.json.br" />
     <mimeMap fileExtension=".symbols.json.br" mimeType="application/octet-stream" />
   </staticContent>

   <!--
     Hosting compressed Unity builds without decompression fallback relies on native browser decompression,
     therefore a proper "Content-Encoding" response header should be added for the compressed build files.
     NOTE: IIS will throw an exception if the following section is used without the "URL Rewrite" module installed.
     Download the "URL Rewrite" module from https://www.iis.net/downloads/microsoft/url-rewrite
   -->
   <rewrite>
     <outboundRules>
       <!--
         NOTE: IIS will throw an exception if the same rule name is used multiple times.
         To avoid possible conflicts with configurations that are already on the server, you should remove the mimeType for the corresponding extension using the <remove> element,
       before adding mimeType using the <mimeMap> element.
       -->
       <!-- The following section is required for builds compressed with gzip, which don't include decompression fallback. -->
       <remove name="Append gzip Content-Encoding header" />
       <rule name="Append gzip Content-Encoding header">
         <match serverVariable="RESPONSE_Content-Encoding" pattern=".*" />
         <conditions>
           <add input="{REQUEST_FILENAME}" pattern="\.gz$" />
         </conditions>
         <action type="Rewrite" value="gzip" />
       </rule>
       <!-- The following section is required for builds compressed with Brotli, which don't include decompression fallback. -->
       <remove name="Append brotli Content-Encoding header" />
       <rule name="Append brotli Content-Encoding header">
         <match serverVariable="RESPONSE_Content-Encoding" pattern=".*" />
         <conditions>
           <add input="{REQUEST_FILENAME}" pattern="\.br$" />
         </conditions>
         <action type="Rewrite" value="br" />
       </rule>
     </outboundRules>
   </rewrite>
 </system.webServer>
</configuration>

Server configuration for uncompressed WebGL builds (IIS)

<?xml version="1.0" encoding="UTF-8"?>
<!--
 The following server configuration can be used for uncompressed WebGL builds.
 This configuration file should be uploaded to the server as "<Application Folder>/Build/web.config"
-->
<configuration>
 <system.webServer>
   <!--
     IIS does not provide default handlers for .data and .wasm files (and in some cases .json files),
     therefore these files won’t be served unless their mimeType is explicitly specified.
   -->
   <staticContent>
     <!--
       NOTE: IIS will throw an exception if a mimeType is specified multiple times for the same extension.
       To avoid possible conflicts with configurations that are already on the server, you should remove the mimeType for the corresponding extension using the <remove> element,
       before adding mimeType using the <mimeMap> element.
     -->
     <remove fileExtension=".data" />
     <mimeMap fileExtension=".data" mimeType="application/octet-stream" />
     <remove fileExtension=".wasm" />
     <mimeMap fileExtension=".wasm" mimeType="application/wasm" />
     <remove fileExtension=".symbols.json" />
     <mimeMap fileExtension=".symbols.json" mimeType="application/octet-stream" />
   </staticContent>
 </system.webServer>
</configuration>
イワケンイワケン

Memory in WebGL

Memory constraints in Unity WebGL can restrict the complexity of the content you can run.
WebGL content runs in the browser. The browser allocates the memory in its memory space that your application needs to run your content. The amount of available memory varies depending on:

Unity WebGL のメモリ制約により、実行可能なコンテンツの複雑さが制限されることがあります。

WebGL コンテンツはブラウザで実行されます。ブラウザは、アプリケーションでコンテンツを実行するために必要なメモリをメモリスペースに割り当てます。利用可能なメモリの量は、以下の条件によって変化します。

  • Which device you use

  • Which operating system you use

  • Which browser you use, and whether it runs on a 32 or 64 processor

  • How much memory the browser’s JavaScript engine requires to parse your code

  • Whether the browser uses separate processes for each tab, or your content needs to share a memory space with all other open tabs.

  • デバイス

  • OS

  • ブラウザ

  • 32bit or 64bit

  • JavaScriptエンジンが必要としているブラウザのメモリ

  • ブラウザのタブごとに個別のプロセスを使用しているか、それともメモリ空間を共有する必要があるか

Unity WebGL コンテンツでは、ブラウザに大量のメモリを確保させる必要がある箇所がいくつかあります。

Unity heap

Unity uses a memory heap to store all Unity engine runtime objects. These include managed and native objects, loaded Assets, Scenes and shaders. This is like the memory that Unity Players use on any other platform.

Unity はメモリヒープを使用して、Unity エンジンのすべてのランタイムオブジェクトを格納します。これにはマネージドオブジェクト、ネイティブオブジェクト、ロードされたAsset、Scene、シェーダーが含まれます。これは、他のプラットフォームでUnityプレイヤーが使用するメモリと同じです。

The Unity heap is a contiguous block of allocated memory. Unity supports automatic resizing for the heap to suit the needs of the application. The heap size expands as an application runs, and can expand up to 2GB. Unity creates this memory heap as a Memory object. The Memory object’s buffer property is a resizable ArrayBuffer that holds the raw bytes of memory accessed by WebAssembly code.

Unityのヒープとは、割り当てられたメモリの連続したブロックのことです。Unityは、アプリケーションのニーズに合わせてヒープの自動リサイズをサポートしています。ヒープサイズはアプリケーションの実行に伴って拡張され、最大で 2GB まで拡張できます。UnityはこのメモリヒープをMemoryオブジェクトとして作成します。Memory オブジェクトの buffer プロパティはサイズ変更可能な ArrayBuffer で、WebAssembly コードがアクセスするメモリの生のバイトを保持します。

Automatic resizing of the heap can cause your application to crash if the browser fails to allocate a contiguous memory block in the address space. For this reason, it is important to keep the Unity heap size as small as possible. Therefore, be mindful when you are planning the memory usage of your application. If you want to test the size of your Unity heap, you can use the Profiler to profile the contents of the memory block.

ヒープの自動リサイズは、ブラウザがアドレス空間に連続したメモリブロックを割り当てられなかった場合に、アプリケーションをクラッシュさせる可能性があります。このため、Unityのヒープサイズをできるだけ小さくしておくことが重要です。したがって、アプリケーションのメモリ使用量を計画するときは、注意してください。Unityヒープのサイズをテストしたい場合は、Profilerを使用してメモリブロックの内容をプロファイルすることができます。

アセットデータ

When you create a Unity WebGL build, Unity generates a .data file. This contains all the Scenes and Assets the application needs to launch. Because Unity WebGL does not have access to the real file system, it creates a virtual memory file system, and the browser unpacks the .data file here. The Emscipten framework (JavaScript) allocates this memory file system in the browser memory space. While your content runs, the browser memory keeps the uncompressed data. To keep both download times and memory usage low, try to keep this uncompressed data as small as possible.

Unity WebGL ビルドを作成すると、Unity は .data ファイルを生成します。これには、アプリケーションが起動するために必要なすべての Scenes と Assets が含まれています。Unity WebGL は実際のファイルシステムにアクセスできないため、仮想メモリファイルシステムを作成し、ブラウザはここで .data ファイルを解凍します。Emscipten フレームワーク(JavaScript)は、このメモリファイルシステムをブラウザのメモリ空間に割り当てます。コンテンツが実行されている間、ブラウザのメモリは圧縮されていないデータを保持します。ダウンロード時間とメモリ使用量の両方を低く抑えるために、この解凍されたデータをできるだけ小さくするようにしてください。

To reduce memory use, you can pack your Asset data into AssetBundles. AssetBundles allow you full control over your Asset downloads. This means that you can control when your application downloads an Asset, and when the runtime unloads it. Unloading unused Assets frees up memory.

メモリ使用量を削減するために、アセットデータをAssetBundleにまとめることができます。AssetBundleを使えば、Assetのダウンロードを完全にコントロールすることができます。つまり、アプリケーションがアセットをダウンロードするタイミングと、ランタイムがそれをアンロードするタイミングを制御することができます。未使用のAssetをアンロードすることで、メモリを解放することができます。

AssetBundles download directly into the Unity heap, so these don’t result in extra allocation by the browser.
AssetBundlesはUnityのヒープに直接ダウンロードされるので、ブラウザによる余分な割り当ては発生しません。

Enable Data Caching to automatically cache the Asset data in your content on the user’s machine. This means you don’t need to re-download that data during later runs. The Unity WebGL loader implements Data Caching with the IndexedDB API. This option allows you to cache files which are too large for the browser to cache natively.

データキャッシングを有効にすると、コンテンツ内のアセットデータがユーザーのマシンに自動的にキャッシュされます。これは、後で実行する際にデータを再ダウンロードする必要がないことを意味します。Unity WebGL ローダーは IndexedDB API を使用して Data Caching を実装しています。このオプションを使用すると、ブラウザがネイティブでキャッシュするには大きすぎるファイルをキャッシュすることができます。

Data caching enables the browser to store application data on the user’s machine. Browsers often limit the amount you can store in their cache and the maximum file size that can be cached. This is often not enough for an application to run smoothly. Therefore the Unity WebGL loader implements Date Caching with the IndexedDB API. Instead of storing the content in the browser cache, Unity stores the data in the IndexedDB.

データキャッシュは、ブラウザがユーザーのマシンにアプリケーションデータを保存することを可能にします。ブラウザは多くの場合、キャッシュに保存できる量と、キャッシュできる最大ファイルサイズを制限しています。これでは、アプリケーションをスムーズに動作させるのに十分でないことがよくあります。そこで、Unity WebGL ローダーは IndexedDB API を使用して日付キャッシュを実装しています。ブラウザのキャッシュにコンテンツを保存する代わりに、Unity は IndexedDB にデータを保存します。

Large-Allocation HTTP header

あなたのサーバーは、あなたのコンテンツに対して Large-Allocation HTTP ヘッダを発行することができます。これは、サポートされているブラウザ (現在は Mozilla Firefox のみ) にメモリの必要性を知らせます。この情報により、サポートされるブラウザは断片化されていないメモリ空間を使用して新しいプロセスを生成することができます。また、ブラウザは大規模な割り当てが成功するように、特別な管理を行うことができます。これにより、Unityヒープを割り当てようとしたときに、ブラウザがメモリ不足になる問題を解決できます。これは特に32ビットブラウザで重要です。

Garbage collection considerations

Garbage collection is the process of locating and freeing up unused memory. Once the garbage collector collects unused memory it reallocates it inside the Unity heap.
ガベージコレクションとは、未使用のメモリを特定し、解放するプロセスです。ガベージコレクタは、未使用のメモリを収集すると、それをUnityヒープ内に再割り当てします。

For an overview on how Unity garbage collection works, see Automatic Memory Management. WebGL garbage collection runs when the stack is empty. The stack is a part of the Unity heap but not the heap itself. This usually occurs after every frame. This is different from the garbage collection process on other platforms, where the collector pauses all running threads so it can inspect the stack. This is not possible in JavaScript. You can debug the garbage collection process using the Unity Profiler.

Unity のガベージコレクションの仕組みの概要については、「自動メモリ管理」をご覧ください。WebGL のガベージコレクションは、スタックが空になったときに実行されます。スタックは Unity のヒープの一部であり、ヒープそのものではありません。これは通常、毎フレーム後に発生します。これは他のプラットフォームのガベージコレクションプロセスとは異なり、コレクターは実行中のすべてのスレッドを一時停止して、スタックを検査することができます。これは JavaScript では不可能です。ガベージコレクションプロセスは Unity Profiler を使ってデバッグすることができます。

On most other platforms garbage collection pauses all running threads. The garbage collector will then inspect their stacks and register for loaded object references. This is not currently possible in JavaScript. For this reason, the garbage collector will only run in WebGL in situations where the stack is empty. This currently happens once after every frame.

他のほとんどのプラットフォームでは、ガベージコレクションは実行中のすべてのスレッドを一時停止します。そして、ガベージコレクタはそれらのスタックを検査し、ロードされたオブジェクトの参照について登録します。これは現在のところ JavaScript では不可能です。このため、ガベージコレクタは WebGL ではスタックが空になったときのみ実行されます。これは現在、すべてのフレームの後に一度だけ起こります。

このため、以下のコードは WebGL 上で実行すると失敗します。これは、ループの反復の間にガベージコレクタが実行される機会がないためです。つまり、ガベージコレクタは、中間文字列オブジェクトが使用するメモリを解放できず、Unity ヒープ内のメモリが不足する可能性が高いのです。

string hugeString = "";
 
for (int i = 0; i < 100000; i++)
 
{
 
  hugeString += "foo";
 
}
イワケンイワケン

WebGL performance considerations WebGLのパフォーマンスに関する考察

In general, the WebGL performance is close to native apps on the GPU, because the WebGL graphics API uses your GPU for hardware-accelerated rendering. The only exception is the slight overhead for translating WebGL API calls and shaders to your OS graphics API (typically DirectX on Windows, OpenGL on Mac, and Linux).
一般に、WebGL グラフィック API は GPU を使用してハードウェア アクセラレーションによるレンダリングを行うため、GPU 上のネイティブ アプリケーションに近いパフォーマンスが得られます。唯一の例外は、WebGL の API 呼び出しとシェーダーを OS のグラフィックス API(通常、Windows では DirectX、Mac および Linux では OpenGL)に変換するためのわずかなオーバーヘッドが発生することです。

On the CPU, Emscripten translates your code into WebAssembly, the performance of which depends on the web browser you’re using. For more information, see the Unity blog post WebAssembly Load Times and Performance.

CPU では、Emscripten がコードを WebAssembly に変換しますが、その性能は使用している Web ブラウザに依存します。詳細については、Unity ブログの記事「WebAssembly Load Times and Performance」を参照してください。

Following are the additional considerations that you must be aware of: * The JavaScript language does not support multi-threading or SIMD. * Any code that benefits from these features are likely to be slower than other code. * You cannot write threading or SIMD code in WebGL in your scripts, but as some engine parts are multi-threaded or SIMD optimized, they offer low performance on WebGL. For example, WebGL Skinning is both multi-threaded and SIMD-optimized.

以下は、注意すべき追加事項です。

  • JavaScript 言語はマルチスレッドや SIMD をサポートしていません。
  • WebGL のスレッドや SIMD のコードをスクリプトに書くことはできませんが、いくつかのエンジン部分はマルチスレッドや SIMDに最適化されているので、WebGL では低いパフォーマンスを提供します。
    • たとえば、WebGLのSkinningはマルチスレッドと SIMD の両方に最適化されています。

Tip: To see how Unity distributes work to different threads on non-WebGL platforms, see the new timeline Profiler in Unity.

ヒント: WebGL 以外のプラットフォームで、Unity がどのように異なるスレッドに作業を分配しているかを確認するには、Unity の新しいタイムライン プロファイラーを参照してください。

WebGL-specific settings which affect performance パフォーマンスに影響を与えるWebGL固有の設定

For best performance, set the optimization level to Faster in the Build Player window, and set Exception support to None in the Player settings for WebGL by expanding Other Settings > Stack Trace.

最高のパフォーマンスを得るには、Build Playerウィンドウで最適化レベルをFasterに設定し、Other Settings > Stack Traceを展開してWebGLのPlayer settingsでException supportをNoneに設定してください。

WebGL content in background tabs

Run in background が WebGL プラットフォームのプレイヤー設定 で有効になっている場合、または Application.runInBackground を有効にする場合、キャンバスやブラウザーウィンドウがフォーカスを失っても、コンテンツは引き続き実行されます。

WebGL パフォーマンスの減速

You might want to run your WebGL content at a lower frame rate in some situations to reduce CPU usage. For example, on other platforms, you can use the Application.targetFrameRate API to do so.

When you don’t want to throttle performance, set this API to the default value of –1, rather than to a high value. This allows the browser to adjust the frame rate for the smoothest animation in the browser’s render loop, and might produce better results than Unity trying to do its own main loop timing to match a target frame rate.

CPU 使用率を減らすために、状況によっては低いフレームレートで WebGL コンテンツを実行したい場合があります。たとえば、他のプラットフォームでは、Application.targetFrameRate API を使用してそのようにすることができます。

パフォーマンスを調整したくない場合は、この API を高い値ではなく、デフォルトの値である -1 に設定します。これにより、ブラウザのレンダリングループで最もスムーズなアニメーションのためにフレームレートを調整することができ、Unityがターゲットフレームレートに合わせて独自のメインループタイミングを行おうとするよりも良い結果を生む可能性があります。

イワケンイワケン

Debugging and troubleshooting WebGL builds WebGLビルドのデバッグとトラブルシューティング

Visual Studio does not support debugging Unity WebGL
content. To help you to find out exactly what’s going on with your content, here are some tips on how to get information out of your build.

Visual Studio は Unity WebGL のデバッグをサポートしていません。
コンテンツのデバッグをサポートしていません。コンテンツで何が起こっているのかを正確に知るために、ビルドから情報を取得する方法のヒントをご紹介します。

The browser’s JavaScript console

Unity WebGL はファイルシステムにアクセスできないので、他のプラットフォームのようにログファイルを書きません。ただし、すべてのログ情報(Debug.Log、Console.WriteLine、Unity の内部ログなど)は、ブラウザの JavaScript コンソールに書き込まれます。

JavaScript コンソールを開くには、以下の手順を行います。

  • Firefox では、Ctrl-Shift-K (Windows)、または Command-Option-K (Mac) を押します。
  • Chrome では、Ctrl-Shift-J (Windows)、または Command-Option-J (Mac) を押します。
  • Safari では、Preferences > Advanced > Develop の順に移動し、Command-Option-C を押します。
  • Microsoft Edge または Internet Explorer で、F12 を押します。

開発ビルド

デバッグの目的で、Unity で開発ビルドを作成したい場合があります (Build Settings ウィンドウ を開き、Development Build チェックボックスにチェックします)。開発ビルドでは、プロファイラーを接続することができ、Unity はそれらをminify (ミニファイ) しません。そのため、生成された JavaScript コードには人間が読める ( C++ 名前修飾 ですが) 関数名が含まれています。ブラウザーエラーが発生した時、 Debug.LogError の使用時、または、例外をスローし例外サポートが無効になった時に、ブラウザーは上記を利用してスタックトレースを表示することができます。例外的なサポートが完全にサポートされている場合 (以下を参照) に発生するマネージスタックトレースとは異なり、これらのスタックトレースは名前修飾した名前を持ち、マネージコードだけでなく内部の UnityEngine コードも含みます。

例外のサポート

イワケンイワケン

https://docs.unity3d.com/ja/current/Manual/webgl-input.html

Input in WebGL

Gamepad and Joystick support

Unity WebGL supports Input and InputSystem for gamepads and joysticks for browsers that support the HTML5 Gamepad API.

Some browsers only allow access to input devices after the end user interacts with the device while the application has focus. This is a security measure that prevents the end user using connected devices for browser fingerprinting purposes. For this reason, your application should instruct the user to press a button on their gamepad/joystick before you call Input.GetJoystickNames() to check for connected devices.

Unity WebGLは、HTML5 Gamepad APIをサポートするブラウザのために、ゲームパッドとジョイスティックのInputとInputSystemをサポートしています。

ブラウザによっては、アプリケーションにフォーカスがあるときにエンドユーザーがデバイスと対話した後にのみ、入力デバイスへのアクセスを許可するものがあります。これは、エンドユーザーがブラウザのフィンガープリント目的で接続デバイスを使用するのを防ぐためのセキュリティ対策です。このため、Input.GetJoystickNames()を呼び出して接続デバイスをチェックする前に、アプリケーションでユーザーにゲームパッド/ジョイスティックのボタンを押すように指示する必要があります。

Touch support

Unity WebGL doesn’t officially support mobile devices (see WebGL browser compatibility) but it does implement Input.touches and other related APIs in browsers and devices with touch support.
Unity WebGL は公式にはモバイル機器をサポートしていませんが(WebGL ブラウザの互換性を参照)、タッチをサポートするブラウザやデバイスでは Input.touches およびその他の関連 API を実装しています。

Keyboard input and focus handling

デフォルトでは、Unity WebGL は、WebGL キャンバスにフォーカスがあるかどうかに関係なく、Web ページが受け取るすべてのキーボード入力を処理します。これは、エンドユーザーが WebGL キャンバスをクリックすることなく、キーボードベースのアプリケーションを使い始めることができるようにするためです。

重要:ページ上にテキストフィールドなど、キーボード入力を受け取るべき他の HTML 要素がある場合、問題が発生する可能性があります。Unity は、ページの他の部分が入力イベントを受信する前に消費します。HTML 要素でキーボード入力を受け取るようにするには、WebGLInput.captureAllKeyboardInput を false に設定します。この場合、アプリケーションは WebGL canvas にフォーカスがある場合にのみ入力を受け取ります。

Mobile Sensor support

Unity WebGL doesn’t officially support mobile devices (see WebGL browser compatibility) but, for browsers and mobile devices with touch support, Unity WebGL includes support for the following sensors:
Unity WebGL はモバイルデバイスを公式にサポートしていませんが(WebGL ブラウザの互換性を参照)、タッチをサポートするブラウザやモバイルデバイスのために、Unity WebGL は以下のセンサーをサポートしています。

  • Accelerometer with Input.acceleration
  • LinearAcceleration with Gyroscope.userAcceleration
  • Gyroscope with Gyroscope.rotationRate
  • Gravity with Gyroscope.gravity
  • Attitude with Gyroscope.attitude
  • The Input System package also supports these sensors.

Important: Browsers only allow sensor input in secure contexts. This means you must serve the page over HTTPS. The single exception is http://localhost, which you can use during development.

重要: ブラウザは安全なコンテキストでのみセンサーの入力を許可します。つまり、ページを HTTPS で提供する必要があります。唯一の例外は、http://localhost、開発中に使用することができます。

イワケンイワケン

WebGL のネットワーク

WebGLでは、次の2つの方法でネットワークを利用することができます。

  • UnityWebRequest class
  • Unity Multiplayer (previously UNet)

Note: UNet is a deprecated solution, and a new Multiplayer and Networking Solution (Netcode for GameObjects) is under development.
注:UNetは非推奨のソリューションであり、新しいMultiplayer and Networking Solution(Netcode for GameObjects)は現在開発中です。

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

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

This page contains guidelines on how to use networking in WebGL.
このページでは、WebGLでネットワークを利用するためのガイドラインを紹介します。

Using 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 は WebGL の UnityWebRequest クラスをサポートしています。UnityWebRequest クラスを実装するために、Unity は JavaScript Fetch API を使用しており、ブラウザを使用して Web リクエストを処理します。このため、クロスドメインのリソースにアクセスする際にセキュリティ上の制約が生じます。

If you send a web request to a server other than the one that hosts the Unity content, the server you’re sending it to must authorise the Unity content.
Unityのコンテンツをホストしているサーバー以外のサーバーにWebリクエストを送信する場合、送信先のサーバーがUnityのコンテンツを認可する必要があります。

To access cross-domain web resources in WebGL, the server you are trying to access needs to use cross-origin resource sharing (CORS) to authorize cross-domain web resources.
WebGLでクロスドメインのWebリソースにアクセスするには、アクセス先のサーバーがCORS(cross-origin resource sharing)を使用してクロスドメインのWebリソースを認可する必要があります。

If you try to access content using UnityWebRequest, and the remote server does not have CORS set up or configured correctly, an error like the following appears in the browser console:
UnityWebRequestを使用してコンテンツにアクセスしようとしたときに、リモートサーバーにCORSが設定されていない、または正しく設定されていない場合、ブラウザコンソールに次のようなエラーが表示されます。

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

The server needs to add Access-Control headers to the http responses it sends out, to indicate which web pages have permission to read that information from a web browser.
サーバーは、送信するhttpレスポンスにAccess-Controlヘッダーを追加して、どのWebページがWebブラウザからその情報を読み取る許可を持っているかを示す必要があります。

For a demonstration of how to add Access-Control headers that allow Unity WebGL to access resources on a web server from any origin, see the following example. This example includes common request headers and allows the GET, POST or OPTIONS methods:
Unity WebGL が任意のオリジンから Web サーバー上のリソースにアクセスできるように Access-Control ヘッダーを追加する方法については、次の例を参照してください。この例では、一般的なリクエストヘッダーを含み、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 downloads

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

while(!www.isDone) {}

You cannot 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.

UnityWebRequest のダウンロードが完了するのを待つためにスレッドをブロックすることはできませんし、そうしなければアプリケーションがフリーズします。WebGL はシングルスレッドで、JavaScript の fetch API は非同期なので、ブラウザに制御を戻さない限り、ダウンロードが終了しない可能性があります。代わりに、コルーチンと yield 文を使用して、ダウンロードが終了するのを待ちます。詳しくは、「UnityWebRequestを使ったコルーチンの例」をご覧ください。

Using WebSockets or WebRTC from JavaScript

WebGL does not 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 does not 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 は IP ソケットに直接アクセスできませんが、WebSocket または WebRTC(ブラウザがサポートする最も一般的な 2 つのネットワーク プロトコル)を使用してこれを回避することができます。WebSocket は広くサポートされていますが、WebRTC はブラウザ間のピアツーピア接続を可能にし、信頼性の低い接続を可能にします。Unity には WebSocket や WebRTC を利用するための API が組み込まれていませんが、JavaScript プラグインを使用して実装することができます。WebSocket ネットワークを実装するプラグインは Unity Asset Storeで見つけることができます。

イワケンイワケン

Building your WebGL application

Build Settings

  • Texture Compression(Texture圧縮)
    • Use default format (DXT)
    • ETC
    • ETC2
    • ASTC
      • このテクスチャ圧縮フォーマットは、派生する圧縮率の幅が広いため、人気のある選択肢です。たとえば、ASTC 圧縮はほとんどの Intel GPU と Nvidia Tegra チップ で利用可能です。
    • DXT
  • Development Build
    • この設定を有効にすると、ビルドにスクリプトのデバッグシンボルとProfilerが含まれます。この設定を有効にすると、Unity は DEVELOPMENT_BUILD スクリプト定義を設定します。この設定は、アプリケーションをテストする場合にのみ使用する必要があります。開発ビルドはコンテンツを最小化しないので、配布する際に非常に大きくなることに注意してください。
  • Code Optimization
    • Speed (default)
      • ランタイムパフォーマンスに最適化された WebGL コードが生成されます。
    • Size
      • ビルド サイズに合わせて最適化された WebGL コードが生成されます。これは、Android や iOS のモバイル ブラウザで実行する WebGL ゲームを構築する場合に特に便利です。 デフォルトの optimize-for-speed オプションでは、モバイル デバイスが消費する WebAssembly ファイルが大きくなってしまいます。
  • Autoconnect Profiler
    • 通常、この設定を有効にすると、Unity Profiler をビルドに自動的に接続することができます。ただし、WebGLの場合、実行中のビルドにProfilerを接続できないため、このオプションを使用して、代わりにコンテンツをEditorに接続します。これは、WebGLではProfilerの接続はWebSocketを使用して処理されますが、Webブラウザではコンテンツからの発信接続しかできないためです。この設定を利用するためには、Development Build オプションを有効にする必要があります。
  • Deep Profiling Support
    • Profiler で Deep Profiling が有効になります。これにより、Profilerはアプリケーション内のすべての関数呼び出しを計測し、より詳細なプロファイリングデータを返します。Deep Profiling Supportを有効にすると、スクリプトの実行速度が低下する場合があります。このオプションは、Development Buildオプションを有効にした場合のみ使用可能です。
  • IL2CPP Code Generation (
    • Faster runtime
      • ランタイムパフォーマンスに最適化されたコードを生成します。これは、以前のバージョンのUnityにおけるデフォルトの動作です。
    • Faster (smaller) builds
      • ビルドサイズと反復処理に最適化されたコードを生成します。生成されるコードが少なくなり、ビルドも小さくなりますが、特に汎用的なコードでは実行時のパフォーマンスに影響が出る可能性があります。このオプションは、変更を繰り返す場合など、ビルド時間の短縮が重要な場合に使用するとよいでしょう。
イワケンイワケン

Build Folder

Buildフォルダには、以下のファイルが含まれます([ExampleBuild]は対象のビルドフォルダ名を表します)。

File name Contains 日本語
[ExampleBuild].loader.js The JavaScript code that the web page needs in order to load the Unity content. WebページがUnityのコンテンツを読み込むために必要なJavaScriptのコードです。
[ExampleBuild].framework.js JavaScript runtime and plugins. JavaScriptランタイムとプラグイン。
[ExampleBuild].wasm WebAssembly binary. WebAssemblyのバイナリです。
[ExampleBuild].mem A binary image to initialize the heap memory for your Player. Unity only generates this file for multi-threaded WebAssembly builds. Player のヒープメモリを初期化するためのバイナリイメージです。Unity は、マルチスレッドの WebAssembly ビルドの場合にのみ、このファイルを生成します。
[ExampleBuild].data Asset data and Scenes. アセットデータとシーン
[ExampleBuild].symbols.json Debug symbol names necessary to demangle an error stack trace. This file is only generated for Release builds when you enable the Debug Symbols option エラースタック・トレースをデマッチングするために必要なデバッグ・シンボル名です。このファイルは Release ビルドで Debug Symbols オプションを有効にした場合にのみ生成されます。
[ExampleBuild].jpg A background image, which displays while the build is loading. This file is only generated when a Background Image is provided in the Player Settings ビルドのロード中に表示される背景画像です。このファイルは、プレーヤーの設定で背景画像が提供されている場合にのみ生成されます。