Skip to content

Commit f041121

Browse files
committed
docs: Add documentation
1 parent 823307c commit f041121

File tree

4 files changed

+1362
-0
lines changed

4 files changed

+1362
-0
lines changed

README.md

Lines changed: 338 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,340 @@
11
# unity-webgl
22

3+
[![version](https://img.shields.io/npm/v/unity-webgl?style=flat-square)](https://www.npmjs.com/package/unity-webgl)
4+
[![downloads](https://img.shields.io/npm/dm/unity-webgl?style=flat-square)](https://www.npmjs.com/package/unity-webgl)
5+
[![size](https://img.shields.io/bundlephobia/minzip/unity-webgl?style=flat-square)](https://bundlephobia.com/package/unity-webgl)
6+
[![license](https://img.shields.io/npm/l/unity-webgl?style=flat-square)](https://github.com/Marinerer/unity-webgl)
7+
8+
[ English | [中文](./README.zh_CN.md) ]
9+
10+
`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.
11+
12+
> Framework agnostic, usable in any web project.
13+
> Currently includes Vue components, supporting both Vue 2/3.
14+
15+
Based on [react-unity-webgl](https://github.com/jeffreylanters/react-unity-webgl)
16+
17+
## Features
18+
19+
- 📦 Easy integration, framework-agnostic
20+
- 📩 Bidirectional communication between WebApp and Unity
21+
- ⏰ Comprehensive event handling mechanism
22+
- 🧲 Built-in Vue components (vue2/3)
23+
24+
## Installation
25+
26+
**npm**
27+
28+
```bash
29+
npm install unity-webgl
30+
```
31+
32+
**Browser**
33+
34+
```html
35+
<script src="https://cdn.jsdelivr.net/npm/unity-webgl/dist/index.min.js"></script>
36+
```
37+
38+
## Quick Start
39+
40+
- [Live Demo]()
41+
- [vue2 Demo](https://stackblitz.com/edit/unity-webgl-vue2-demo)
42+
- [vue3 Demo](https://stackblitz.com/edit/unity-webgl-vue3-demo)
43+
44+
> 🚨 **Important:**
45+
> Communication and interaction with the web application are only possible after the Unity instance is successfully created (when the `mounted` event is triggered).
46+
> Recommended to include a loading progress bar when opening the page.
47+
48+
```javascript
49+
import UnityWebgl from 'unity-webgl'
50+
51+
const unityContext = new UnityWebgl('#canvas', {
52+
loaderUrl: 'path/to/unity.loader.js',
53+
dataUrl: 'path/to/unity.data',
54+
frameworkUrl: 'path/to/unity.framework.js',
55+
codeUrl: 'path/to/unity.code',
56+
})
57+
58+
unityContext
59+
.on('progress', (progress) => console.log('Loaded: ', progress))
60+
.on('mounted', () => {
61+
// ⚠️ Unity instance created, ready for communication
62+
unityContext.sendMessage('GameObject', 'ReceiveRole', 'Tanya')
63+
})
64+
65+
// For Unity to call
66+
unityContext.addUnityListener('gameStart', (msg) => {
67+
console.log('from Unity : ', msg)
68+
})
69+
// window.dispatchUnityEvent('gameStart', '{score: 0}')
70+
```
71+
72+
<details>
73+
<summary>Vue Demo</summary>
74+
75+
```html
76+
<script setup>
77+
import UnityWebgl from 'unity-webgl'
78+
import VueUnity from 'unity-webgl/vue'
79+
80+
const unityContext = new UnityWebgl({
81+
loaderUrl: 'path/to/unity.loader.js',
82+
dataUrl: 'path/to/unity.data',
83+
frameworkUrl: 'path/to/unity.framework.js',
84+
codeUrl: 'path/to/unity.code',
85+
})
86+
87+
unityContext.addUnityListener('gameStart', (msg) => {
88+
console.log('from Unity : ', msg)
89+
})
90+
</script>
91+
92+
<template>
93+
<VueUnity :unity="unityContext" width="800" height="600" />
94+
</template>
95+
```
96+
97+
</details>
98+
99+
## API
100+
101+
### Constructor
102+
103+
```typescript
104+
new UnityWebgl(canvas: HTMLCanvasElement | string, config?:UnityConfig)
105+
106+
// or
107+
108+
const unityContext = new UnityWebgl(config: UnityConfig)
109+
unityContext.create(canvas: HTMLCanvasElement | string)
110+
```
111+
112+
- `canvas` : Render Unity canvas elements or selectors.
113+
- `config` : Initializes the Unity application's configuration items.
114+
115+
#### config
116+
117+
Initializes the Unity application's configuration items.
118+
119+
| Property | Type | Description | Required |
120+
| ------------------------ | ------- | -------------------------------------------------------------------------------------------------- | -------- |
121+
| `loaderUrl` | string | Unity resource loader file ||
122+
| `dataUrl` | string | File containing resource data and scenes ||
123+
| `frameworkUrl` | string | File with runtime and plugin code ||
124+
| `codeUrl` | string | WebAssembly binary file with native code ||
125+
| `streamingAssetsUrl` | string | URL for streaming resources | Optional |
126+
| `memoryUrl` | string | URL for generated framework files | Optional |
127+
| `symbolsUrl` | string | URL for generated Unity code files | Optional |
128+
| `companyName` | string | Metadata: Company name | Optional |
129+
| `productName` | string | Metadata: Product name | Optional |
130+
| `productVersion` | string | Metadata: Product version | Optional |
131+
| `devicePixelRatio` | number | Canvas device pixel ratio. @see[devicePixelRatio][devicePixelRatio-url] | Optional |
132+
| `matchWebGLToCanvasSize` | boolean | Disable automatic WebGL canvas size sync. @see[matchWebGLToCanvasSize][matchWebGLToCanvasSize-url] | Optional |
133+
| `webglContextAttributes` | object | WebGL rendering context options. @see[WebGLRenderingContext][webglContextAttributes-url] | Optional |
134+
135+
[devicePixelRatio-url]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
136+
[matchWebGLToCanvasSize-url]: https://issuetracker.unity3d.com/issues/webgl-builds-dont-allow-separate-control-on-canvas-render-buffer-size
137+
[webglContextAttributes-url]: https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getContextAttributes
138+
139+
### Methods
140+
141+
**Instance methods :**
142+
143+
#### ⭐️ `create(canvas: HTMLCanvasElement | string): void;`
144+
145+
Create a Unity WebGL instance on the specified canvas.
146+
147+
- `canvas` : canvas element
148+
149+
```javascript
150+
await unityContext.create('#canvas')
151+
```
152+
153+
#### ⭐️ `unload(): Promise<void>;`
154+
155+
Unload the Unity WebGL instance.
156+
157+
```javascript
158+
await unityContext.unload()
159+
```
160+
161+
#### ⭐️ `sendMessage(objectName: string, methodName: string, value?: any): this;`
162+
163+
Send a message to invoke a public method in the Unity scene.
164+
165+
- `objectName`: Object Name in Unity Scene
166+
- `methodName`: Unity script method name
167+
- `value`: Passed value
168+
169+
```javascript
170+
unityContext.sendMessage('GameObject', 'gameStart', { role: 'Tanya' })
171+
```
172+
173+
#### `requestPointerLock(): void;`
174+
175+
Request pointer lock on the Unity canvas.
176+
177+
#### `takeScreenshot(dataType?: string, quality?: any): string | undefined;`
178+
179+
Capture a screenshot of the Unity canvas.
180+
181+
- `dataType`: Type of image data
182+
- `quality`: Image quality
183+
184+
```javascript
185+
const screenshot = unityContext.takeScreenshot('image/jpeg', 0.92)
186+
```
187+
188+
#### `setFullscreen(enabled: boolean): void;`
189+
190+
Toggle fullscreen mode.
191+
192+
```javascript
193+
unityContext.setFullscreen(true)
194+
```
195+
196+
**Event methods :**
197+
198+
#### `on(name: string, listener: EventListener, options?: { once?: boolean }): this;`
199+
200+
Register for listening events.
201+
202+
```javascript
203+
unityContext.on('progress', (progress) => {
204+
console.log('Progress:', progress)
205+
})
206+
```
207+
208+
#### `off(name: string, listener?: EventListener): this;`
209+
210+
Remove event listener.
211+
212+
```javascript
213+
unityContext.off('progress', listener)
214+
```
215+
216+
**Unity Communication methods :**
217+
218+
#### `addUnityListener(name: string, listener: EventListener, options?: { once?: boolean }): this;`
219+
220+
Register a specific listener for Unity to call.
221+
222+
```javascript
223+
unityContext.addUnityListener('GameStarted', (level) => {
224+
console.log('Game started at level:', level)
225+
})
226+
227+
// then call it in Unity
228+
window.dispatchUnityEvent('GameStarted', 3)
229+
```
230+
231+
#### `removeUnityListener(name: string, listener?: EventListener): this;`
232+
233+
Remove registered listeners.
234+
235+
```javascript
236+
unityContext.removeUnityListener('GameStarted', listener)
237+
```
238+
239+
### `window.dispatchUnityEvent(name: string, ...args: any[])`
240+
241+
The way to dispatch a registered listener on the Unity side. (Calling JS methods in unity)
242+
243+
```javascript
244+
window.dispatchUnityEvent('GameStarted', 3)
245+
```
246+
247+
### Events
248+
249+
| Event Name | Description |
250+
| --------------- | ---------------------------------------- |
251+
| `beforeMount` | Triggered before Unity instance creation |
252+
| `mounted` | Triggered after Unity instance creation |
253+
| `beforeUnmount` | Triggered before Unity instance unload |
254+
| `unmounted` | Triggered after Unity instance unload |
255+
| `progress` | Unity resource loading progress |
256+
| `error` | Error events |
257+
| `debug` | Debug messages from Unity |
258+
259+
## Unity-JavaScript Communication
260+
261+
- [Unity Docs: Interaction with browser scripting](https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html)
262+
263+
### 1. Call Unity script functions from JavaScript
264+
265+
```javascript
266+
const unityContext = new UnityWebgl()
267+
268+
/**
269+
* @param {string} objectName Name of an object in your scene.
270+
* @param {string} methodName Public method name.
271+
* @param {any} value Passed value.
272+
*/
273+
unityContext.sendMessage('GameObject', 'StartGame', { role: 'Tanya' })
274+
```
275+
276+
### 2. Call JavaScript functions from Unity scripts
277+
278+
1. First register the listener for Unity to call via `addUnityListener` on the web side.
279+
280+
```javascript
281+
unityContext.addUnityListener('gameStart', (level) => {
282+
console.log('Game started at level:', level)
283+
})
284+
```
285+
286+
2. Add the registered `gameStart` method to your Unity project.
287+
288+
```javascript
289+
// javascript_extend.jslib
290+
mergeInto(LibraryManager.library, {
291+
Hello: function () {
292+
window.alert('Hello, world!')
293+
},
294+
295+
GameStart: function (level) {
296+
//window.alert(UTF8ToString(str));
297+
window.dispatchUnityEvent('gameStart', UTF8ToString(level))
298+
},
299+
})
300+
```
301+
302+
3. Call these functions in unity's `C#` scripts:
303+
304+
```csharp
305+
using UnityEngine;
306+
using System.Runtime.InteropServices;
307+
308+
public class WebGLPluginJS : MonoBehaviour
309+
{
310+
[DllImport("__Internal")]
311+
public static extern void Hello();
312+
313+
[DllImport("__Internal")]
314+
public static extern void GameStart(string level);
315+
316+
void Start()
317+
{
318+
Hello();
319+
GameStart("2");
320+
}
321+
}
322+
```
323+
324+
## Issues
325+
326+
- [Keyboard Input and Focus Handling](https://docs.unity3d.com/Manual/webgl-input.html)
327+
- [Debug and troubleshoot Web builds](https://docs.unity3d.com/Manual/webgl-debugging.html)
328+
- [Web performance considerations](https://docs.unity3d.com/Manual/webgl-performance.html)
329+
330+
## Contributing
331+
332+
Contributions are welcome! Please submit a [Pull Request](https://github.com/Marinerer/unity-webgl/pulls).
333+
334+
## License
335+
336+
Apache-2.0 License
337+
338+
## Support
339+
340+
For issues or questions, please file an issue on the [GitHub repository](https://github.com/Marinerer/unity-webgl).

0 commit comments

Comments
 (0)