[ English | 中文 ]
unity-webgl
provides an easy solution for embedding Unity WebGL
builds in your web applications, with two-way communication and interaction between your webApp and Unity application with advanced API's.
🚨 Reminder
v4.x
has been updated significantly and the API is not compatible withv3.x
and earlier versions. For upgrades, please refer to Changelogs
Based on react-unity-webgl
- 📦 Easy integration, framework-agnostic
- 📩 Bidirectional communication between WebApp and Unity
- ⏰ Comprehensive event handling mechanism
- 🧲 Built-in Vue components (vue2/3)
npm
npm install unity-webgl
Browser
<script src="https://cdn.jsdelivr.net/npm/unity-webgl/dist/index.min.js"></script>
🚨 Important:
Communication and interaction with the web application are only possible after the Unity instance is successfully created (when themounted
event is triggered).
Recommended to include a loading progress bar when opening the page.
import UnityWebgl from 'unity-webgl'
const unityContext = new UnityWebgl('#canvas', {
loaderUrl: 'path/to/unity.loader.js',
dataUrl: 'path/to/unity.data',
frameworkUrl: 'path/to/unity.framework.js',
codeUrl: 'path/to/unity.code',
})
unityContext
.on('progress', (progress) => console.log('Loaded: ', progress))
.on('mounted', () => {
// ⚠️ Unity instance created, ready for communication
unityContext.sendMessage('GameObject', 'ReceiveRole', 'Tanya')
})
// For Unity to call
unityContext.addUnityListener('gameStart', (msg) => {
console.log('from Unity : ', msg)
})
// window.dispatchUnityEvent('gameStart', '{score: 0}')
Vue Demo
<script setup>
import UnityWebgl from 'unity-webgl'
import VueUnity from 'unity-webgl/vue'
const unityContext = new UnityWebgl({
loaderUrl: 'path/to/unity.loader.js',
dataUrl: 'path/to/unity.data',
frameworkUrl: 'path/to/unity.framework.js',
codeUrl: 'path/to/unity.code',
})
unityContext.addUnityListener('gameStart', (msg) => {
console.log('from Unity : ', msg)
})
</script>
<template>
<VueUnity :unity="unityContext" width="800" height="600" />
</template>
new UnityWebgl(canvas: HTMLCanvasElement | string, config?:UnityConfig)
// or
const unityContext = new UnityWebgl(config: UnityConfig)
unityContext.create(canvas: HTMLCanvasElement | string)
-
canvas
: Render Unity canvas elements or selectors. -
config
: Initializes the Unity application's configuration items.
Initializes the Unity application's configuration items.
Property | Type | Description | Required |
---|---|---|---|
loaderUrl |
string | Unity resource loader file | ✅ |
dataUrl |
string | File containing resource data and scenes | ✅ |
frameworkUrl |
string | File with runtime and plugin code | ✅ |
codeUrl |
string | WebAssembly binary file with native code | ✅ |
streamingAssetsUrl |
string | URL for streaming resources | Optional |
memoryUrl |
string | URL for generated framework files | Optional |
symbolsUrl |
string | URL for generated Unity code files | Optional |
companyName |
string | Metadata: Company name | Optional |
productName |
string | Metadata: Product name | Optional |
productVersion |
string | Metadata: Product version | Optional |
devicePixelRatio |
number | Canvas device pixel ratio. @seedevicePixelRatio | Optional |
matchWebGLToCanvasSize |
boolean | Disable automatic WebGL canvas size sync. @seematchWebGLToCanvasSize | Optional |
webglContextAttributes |
object | WebGL rendering context options. @seeWebGLRenderingContext | Optional |
Instance methods :
Create a Unity WebGL instance on the specified canvas.
-
canvas
: canvas element
await unityContext.create('#canvas')
Unload the Unity WebGL instance.
await unityContext.unload()
Send a message to invoke a public method in the Unity scene.
-
objectName
: Object Name in Unity Scene -
methodName
: Unity script method name -
value
: Passed value
unityContext.sendMessage('GameObject', 'gameStart', { role: 'Tanya' })
Request pointer lock on the Unity canvas.
Capture a screenshot of the Unity canvas.
-
dataType
: Type of image data -
quality
: Image quality
const screenshot = unityContext.takeScreenshot('image/jpeg', 0.92)
Toggle fullscreen mode.
unityContext.setFullscreen(true)
Event methods :
Register for listening events.
unityContext.on('progress', (progress) => {
console.log('Progress:', progress)
})
Remove event listener.
unityContext.off('progress', listener)
Unity Communication methods :
Register a specific listener for Unity to call.
unityContext.addUnityListener('GameStarted', (level) => {
console.log('Game started at level:', level)
})
// then call it in Unity
window.dispatchUnityEvent('GameStarted', 3)
Remove registered listeners.
unityContext.removeUnityListener('GameStarted', listener)
The way to dispatch a registered listener on the Unity side. (Calling JS methods in unity)
window.dispatchUnityEvent('GameStarted', 3)
Event Name | Description |
---|---|
beforeMount |
Triggered before Unity instance creation |
mounted |
Triggered after Unity instance creation |
beforeUnmount |
Triggered before Unity instance unload |
unmounted |
Triggered after Unity instance unload |
progress |
Unity resource loading progress |
error |
Error events |
debug |
Debug messages from Unity |
const unityContext = new UnityWebgl()
/**
* @param {string} objectName Name of an object in your scene.
* @param {string} methodName Public method name.
* @param {any} value Passed value.
*/
unityContext.sendMessage('GameObject', 'StartGame', { role: 'Tanya' })
- First register the listener for Unity to call via
addUnityListener
on the web side.
unityContext.addUnityListener('gameStart', (level) => {
console.log('Game started at level:', level)
})
- Add the registered
gameStart
method to your Unity project.
// javascript_extend.jslib
mergeInto(LibraryManager.library, {
Hello: function () {
window.alert('Hello, world!')
},
GameStart: function (level) {
//window.alert(UTF8ToString(str));
window.dispatchUnityEvent('gameStart', UTF8ToString(level))
},
})
- Call these functions in unity's
C#
scripts:
using UnityEngine;
using System.Runtime.InteropServices;
public class WebGLPluginJS : MonoBehaviour
{
[DllImport("__Internal")]
public static extern void Hello();
[DllImport("__Internal")]
public static extern void GameStart(string level);
void Start()
{
Hello();
GameStart("2");
}
}
Contributions are welcome! Please submit a Pull Request.
Apache-2.0 License
For issues or questions, please file an issue on the GitHub repository.