How slimgabsi/unity-3d-webgl-browser-scripting works
Main Components
• Unity Game Engine (UnityProject): This is where the main game logic, assets, scripts, and other Unity-specific elements reside. It is developed in the Unity Editor and then exported as a WebGL build.
• WebGL Build Components (Build folder & TemplateData): These include UnityLoader.js, the data/wrapper files (WebGLBuild.data, .wasm files, etc.), and support files like UnityProgress.js and CSS. They are essential for rendering the game in a browser.
• Browser and HTML/JS Integration (index.html and js folder): The index page and accompanying JavaScript (onInit.js) serve as the entry point for the web page and handle the initialization and communication with the Unity WebGL content.
• External JavaScript Communication Layer: Embedded in the project through the Plugins folder (plugin.jslib) and custom JavaScript libraries, this layer manages the bidirectional messaging between the Unity runtime and the browser’s native JavaScript environment.
Relationships and Interactions
• The HTML (index.html) loads the UnityLoader.js and other supportive TemplateData scripts to initialize the Unity WebGL content.
• Once loaded, the Unity runtime (generated from the UnityProject) runs in the browser context, displaying the game.
• The onInit.js and any other custom JS scripts on the page communicate via the exposed APIs (often defined in plugin.jslib or other scripting interfaces) to send and receive data/events from the Unity application.
• The flow of data is bidirectional:
• Outbound: Browser JavaScript sends commands or data to Unity.
• Inbound: Unity, using its JS integration capabilities, calls back to functions provided in the external JS.
Architectural Patterns and Design Principles
• Separation of Concerns: The Unity project contains all game logic and assets, while the web page (HTML/JS) deals with supporting UI, integration, and interactivity outside the game.
• Decoupled Communication: Use of event-driven communication between Unity and JavaScript ensures that game logic and web initialization are independent but can interact via clearly defined APIs.
• Modular Structure: The design separates the build (rendering resources), Unity project (development assets), and web layer (hosting and script initialization).