Fundamentals
Before diving into optimization and implementation details, it's important to understand how Unity WebGL works and the technologies involved.
WebGL and WebAssembly
Unity WebGL builds use two key technologies:
- WebGL (Web Graphics Library): An API for rendering 3D graphics in web browsers without plugins. WebGL 1.0 is based on OpenGL ES 2.0, while WebGL 2.0 is based on OpenGL ES 3.0.
- WebAssembly (WASM): A binary instruction format that enables high-performance execution of code in web browsers. Unity compiles your C# code to WebAssembly using IL2CPP and Emscripten.
Unity's WebGL Build Process
When you create a WebGL build in Unity:
- Unity uses IL2CPP to convert your C# code to C++
- The Emscripten compiler converts the C++ code to WebAssembly
- Unity generates HTML, JavaScript, and data files for browser execution
- The resulting build includes:
.wasmfiles containing the compiled code.datafiles containing your assets.jsfiles for loading and running the application.htmlfiles for displaying the content
WebGL 2.0 Support in Unity 2022 LTS
Unity 2022 LTS includes robust support for WebGL 2.0, which brings several advantages:
- Higher quality Standard Shader content
- Support for GPU Instancing and directional lightmaps
- No restrictions on indexing and loops in shader code
- Better overall performance
By default, Unity WebGL builds target WebGL 2.0, with fallback to WebGL 1.0 for browsers that don't support it.
WebGPU Partial Support
Unity 2022 LTS and newer versions have begun introducing partial support for WebGPU, the next-generation graphics API for the web:
- Current Status: Experimental/preview support in Unity 2022 LTS (stable, known issues) and later (unstable, harder to troubleshoot).
- Benefits: Significantly improved performance, better access to modern GPU features
- Browser Support: Currently supported in Chrome and Edge, with Firefox support in development
- Implementation: Requires enabling experimental features in Unity's rendering pipeline
- Considerations: As WebGPU support is still evolving in Unity, developers should implement fallbacks to WebGL
WebGPU offers several advantages over WebGL, including more direct access to GPU capabilities, better multithreading support, and improved compute shader functionality. As browser support expands and Unity's implementation matures, WebGPU is expected to eventually become the preferred graphics API for high-performance web games.
Memory Architecture
Understanding WebGL memory architecture is crucial for optimization:
- Unity Heap: A contiguous block of memory that stores all Unity engine runtime objects;
- Asset Data: Stored in a virtual memory file system created by Emscripten;
- Garbage Collection: Runs at the end of each frame, not during execution as in other platforms.
Updated about 1 month ago
