unity-webgl
Unity WebGL provides an easy solution for embedding Unity WebGL builds in your webApp or Vue.js
project, with two-way communication between your webApp and Unity application with advanced API's.
UnityWebgl.js 提供了一种简单的解决方案,用于在 webApp 或 Vue.js (支持Vue2.x
& Vue3.x
) 项目中嵌入 Unity WebGL,并通过API在 webApp 和 Unity 之间进行双向通信。
based on react-unity-webgl
Features
- 💊 Simple and flexible to use
- 📮 two-way communication (
webApp
, Unity
)
- 🛠 Built-in event handler
- 🧬 Available for
Vue.js
(Vue@2.x & Vue@3.x)
Install
npm & ESM
npm install unity-webgl
To make unity-webgl/vue
work for Vue 2 (<2.7.0
), you need to have @vue/composition-api
installed:
npm i -D @vue/composition-api
browser
https://cdn.jsdelivr.net/npm/unity-webgl/dist/UnityWebgl.umd.js
https://cdn.jsdelivr.net/npm/unity-webgl/dist/VueUnity.umd.js
Usage
in example.html
<canvas id="canvas" style="width: 100%; height: 100%"></canvas>
<button onclick="onDestroy()">Destroy</button>
<button onclick="onLoad()">Reload</button>
<button onclick="onFullscreen()">Fullscreen</button>
<script>
var Unity = new UnityWebgl('#canvas', {
loaderUrl: '/Build/unity.loader.js',
dataUrl: "/Build/unity.data",
frameworkUrl: "/Build/unity.framework.js",
codeUrl: "/Build/unity.wasm"
})
Unity
.on('progress', percent => console.log('Unity Loaded: ', percent))
.on('created', () => console.log('Unity Instance: created.'))
.on('destroyed', () => console.log('Unity Instance: Destroyed.'))
function postMessage() {
Unity.send('objectName', 'methodName', {
id: 'B0001',
name: 'Building#1',
location: [150, 75]
})
}
function onDestroy() {
Unity.destroy()
}
function onLoad() {
Unity.create('#canvas')
}
function onFullscreen() {
Unity.setFullscreen(true)
}
</script>
You can also:
var Unity = new UnityWebgl({
loaderUrl: '/Build/unity.loader.js',
dataUrl: "/Build/unity.data",
frameworkUrl: "/Build/unity.framework.js",
codeUrl: "/Build/unity.wasm",
streamingAssetsUrl: "StreamingAssets",
companyName: "DefaultCompany",
productName: "Unity",
productVersion: "0.1",
})
Unity.create(document.querySelector('#canvas'))
Vue
Vue 2.x
<template>
<VueUnity :unity="unityContext" width="800" heighht="600" />
</template>
<script>
import UnityWebgl from 'unity-webgl'
import VueUnity from 'Unity-webgl/vue'
const Unity = new UnityWebgl({
loaderUrl: '/Build/OUT_BIM.loader.js',
dataUrl: "/Build/OUT_BIM.data",
frameworkUrl: "/Build/OUT_BIM.framework.js",
codeUrl: "/Build/OUT_BIM.wasm",
})
Unity.on('device', () => alert('click device ...'))
export default {
components: {
VueUnity
},
data() {
return {
unityContext: Unity
}
}
}
</script>
Vue 3.x
<script setup lang="ts">
import UnityWebgl from 'Unity-webgl';
import VueUnity from 'Unity-webgl/vue'
const Unity = new UnityWebgl({
loaderUrl: '/Build/OUT_BIM.loader.js',
dataUrl: "/Build/OUT_BIM.data",
frameworkUrl: "/Build/OUT_BIM.framework.js",
codeUrl: "/Build/OUT_BIM.wasm",
})
Unity.on('device', () => alert('click device ...'))
</script>
<template>
<VueUnity :unity="Unity" width="800" heighht="600" />
</template>
API
unityContext = new UnityWebgl(
canvasElement: HTMLCanvasElement | string,
options: IUnityConfig
)
Options
loaderUrl: string
The url to the build json file generated by Unity
dataUrl: string
The url to the build data file generated by Unity
frameworkUrl: string
The url to the framework file generated by Unity
codeUrl: string
The url to the unity code file generated by Unity
streamingAssetsUrl?: string
The url where the streaming assets can be found
companyName?: string
The applications company name
productName?: string
The applications product name
productVersion?: string
The applications product version
webglContextAttributes?: IWebGLContextAttributes
This object allow you to configure WebGLRenderingContext creation options. see MDN@WebGLRenderingContext
devicePixelRatio?: number
Uncomment this to override low DPI rendering on high DPI displays. see MDN@devicePixelRatio
matchWebGLToCanvasSize?: boolean
Uncomment this to separately control WebGL canvas render size and DOM element size. see unity3d@matchWebGLToCanvasSize
Methods
create(canvasElement: HTMLCanvasElement | string)
send(objectName: string, methodName: string, params?: any)
Sends a message to the UnityInstance to invoke a public method.
setFullscreen(enabled: boolean)
Enables or disabled the fullscreen mode of the UnityInstance.
destroy()
Quits the Unity Instance and clears it from memory.
on(eventName: string, eventListener: Function)
Use instance.on()
to register a method for Unity-script call.
once(eventName: string, eventListener: Function)
off(eventName: string)
clear()
emit(eventName: string)
Events
progress
loading progress.
unityContext.on('progress', (number) => {})
loaded
loading completed.
unityContext.on('loaded', () => {})
created
Unity Instance is created.
unityContext.on('created', () => {})
destroyed
Quits the Unity Instance and clears it from memory.
unityContext.on('destroyed', () => {})
Vue component
props
unity: UnityWebgl
width?: string|number
, default: 100%
height?: string|number
, default: 100%
Communication
1. Calling JavaScript functions from Unity scripts
从 Unity 脚本调用 JavaScript 函数
-
First, you should register a showDialog
method, which be bind to the __UnityLib__
global object by default.
先在前端项目中通过 Unity.on()
注册 showDialog
方法,该方法会默认绑定在全局对象__UnityLib__
上。
const Unity = new UnityWebgl()
Unity.on('showDialog', (data) => {
console.log(data)
$('#dialog').show()
})
Unity.emit('showDialog', data)
window[Unity.global_name].showDialog(data)
-
In the Unity project, add the registered showDialog
method to the project, and then call those functions directly from your script code. To do so, place files with JavaScript code using the .jslib
extension under a “Plugins” subfolder in your Assets folder. The plugin file needs to have a syntax like this:
在Unity项目中,将注册的showDialog
方法添加到项目中。注意📢 :请使用 .jslib
扩展名将包含 JavaScript 代码的文件放置在 Assets 文件夹中的“Plugins”子文件夹下。插件文件需要有如下所示的语法:
mergeInto(LibraryManager.library, {
showDialog: function (str) {
var data = Pointer_stringify(str);
__UnityLib__.showDialog(data);
},
Hello: function () {
window.alert("Hello, world!");
}
});
Then you can call these functions from your C# scripts like this:
using UnityEngine;
using System.Runtime.InteropServices;
public class NewBehaviourScript : MonoBehaviour {
[DllImport("__Internal")]
private static extern void Hello();
[DllImport("__Internal")]
private static extern void showDialog(string str);
void Start() {
Hello();
showDialog("This is a string.");
}
}
2. Calling Unity scripts functions from JavaScript
使用 JavaScript 调用 Unity 脚本函数
const Unity = new UnityWebgl()
Unity.send(objectName, methodName, params)
Unity.send('mainScene', 'init', {
id: 'b001',
name: 'building#001',
length: 95,
width: 27,
height: 120
})