{"id":22375031,"url":"https://github.com/marinerer/unity-webgl","last_synced_at":"2025-10-09T20:44:03.672Z","repository":{"id":43894656,"uuid":"431078532","full_name":"Marinerer/unity-webgl","owner":"Marinerer","description":"An easy solution for embedding Unity WebGL builds in web projects, with two-way communication between your webApp and Unity. 🏣 在webApp 或 Vue.js 项目中嵌入 Unity WebGL，并支持通过API在 webApp 和 Unity 之间进行双向通信。","archived":false,"fork":false,"pushed_at":"2025-04-22T12:47:12.000Z","size":9808,"stargazers_count":169,"open_issues_count":0,"forks_count":24,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-04-22T13:51:17.215Z","etag":null,"topics":["unity-player","unity-web","unity-web-player","unity-webgl","unity-webgl-build","vue-unity","vue-unity-webgl"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/unity-webgl","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Marinerer.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-11-23T11:43:32.000Z","updated_at":"2025-04-22T12:47:16.000Z","dependencies_parsed_at":"2024-01-13T17:47:26.476Z","dependency_job_id":"c99f221a-3713-47e7-8b92-c27a31372942","html_url":"https://github.com/Marinerer/unity-webgl","commit_stats":{"total_commits":27,"total_committers":2,"mean_commits":13.5,"dds":"0.14814814814814814","last_synced_commit":"0eb02f85fd8b77efcffab31d4dc5f72ae9b82406"},"previous_names":["marinerer/unitywebgl.js","meqn/unitywebgl.js","marinerer/unity-webgl"],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marinerer%2Funity-webgl","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marinerer%2Funity-webgl/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marinerer%2Funity-webgl/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marinerer%2Funity-webgl/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Marinerer","download_url":"https://codeload.github.com/Marinerer/unity-webgl/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254471060,"owners_count":22076585,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["unity-player","unity-web","unity-web-player","unity-webgl","unity-webgl-build","vue-unity","vue-unity-webgl"],"created_at":"2024-12-04T21:19:17.966Z","updated_at":"2025-10-09T20:43:58.620Z","avatar_url":"https://github.com/Marinerer.png","language":"TypeScript","readme":"# unity-webgl\n\n[![version](https://img.shields.io/npm/v/unity-webgl?style=flat-square)](https://www.npmjs.com/package/unity-webgl)\n[![codecov](https://codecov.io/gh/Marinerer/unity-webgl/graph/badge.svg?token=7J0R98DRUB)](https://codecov.io/gh/Marinerer/unity-webgl)\n[![release](https://img.shields.io/github/actions/workflow/status/Marinerer/unity-webgl/release.yml?style=flat-square)](https://github.com/Marinerer/unity-webgl/releases)\n[![downloads](https://img.shields.io/npm/dm/unity-webgl?style=flat-square)](https://www.npmjs.com/package/unity-webgl)\n[![size](https://img.shields.io/bundlephobia/minzip/unity-webgl?style=flat-square)](https://bundlephobia.com/package/unity-webgl)\n[![license](https://img.shields.io/npm/l/unity-webgl?style=flat-square)](https://github.com/Marinerer/unity-webgl)\n\n[ English | [中文](./README.zh_CN.md) ]\n\n`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.\n\n\u003e 🚨 Reminder\n\u003e\n\u003e `v4.x` has been updated significantly and the API is not compatible with `v3.x` and earlier versions. For upgrades, please refer to [Changelogs](https://github.com/Marinerer/unity-webgl/wiki/Major-changes-in-v4)\n\nBased on [react-unity-webgl](https://github.com/jeffreylanters/react-unity-webgl)\n\n## Features\n\n- 📦 Easy integration, framework-agnostic\n- 📩 Bidirectional communication between WebApp and Unity\n- ⏰ Comprehensive event handling mechanism\n- 🧲 Built-in Vue components (`vue2/3`)\n\n## Installation\n\n**npm**\n\n```bash\nnpm install unity-webgl\n```\n\n**Browser**\n\n```html\n\u003cscript src=\"https://cdn.jsdelivr.net/npm/unity-webgl/dist/index.min.js\"\u003e\u003c/script\u003e\n```\n\n## Quick Start\n\n- [Live Demo](https://stackblitz.com/edit/unity-webgl-v4-demo)\n- [vue3 Demo](https://stackblitz.com/edit/unity-webgl-v4-vue3-demo)\n\n\u003e [!IMPORTANT]\n\u003e\n\u003e Communication and interaction with the web application are only possible after the Unity instance is successfully rendered (when the `mounted` event is triggered).  \n\u003e Recommended to include a loading progress bar when opening the page.\n\n```javascript\nimport UnityWebgl from 'unity-webgl'\n\nconst unityContext = new UnityWebgl('#canvas', {\n\tloaderUrl: 'path/to/unity.loader.js',\n\tdataUrl: 'path/to/unity.data',\n\tframeworkUrl: 'path/to/unity.framework.js',\n\tcodeUrl: 'path/to/unity.code',\n})\n\nunityContext\n\t.on('progress', (progress) =\u003e console.log('Loaded: ', progress))\n\t.on('mounted', () =\u003e {\n\t\t// ⚠️ UnityInstance rendered, ready for communication\n\t\tunityContext.sendMessage('GameObject', 'ReceiveRole', 'Tanya')\n\t})\n\n// For Unity to call\nunityContext.addUnityListener('gameStart', (msg) =\u003e {\n\tconsole.log('from Unity : ', msg)\n})\n// window.dispatchUnityEvent('gameStart', '{score: 0}')\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eVue Demo\u003c/summary\u003e\n\n```html\n\u003cscript setup\u003e\n\timport UnityWebgl from 'unity-webgl'\n\timport VueUnity from 'unity-webgl/vue'\n\n\tconst unityContext = new UnityWebgl({\n\t\tloaderUrl: 'path/to/unity.loader.js',\n\t\tdataUrl: 'path/to/unity.data',\n\t\tframeworkUrl: 'path/to/unity.framework.js',\n\t\tcodeUrl: 'path/to/unity.code',\n\t})\n\n\tunityContext.addUnityListener('gameStart', (msg) =\u003e {\n\t\tconsole.log('from Unity : ', msg)\n\t})\n\u003c/script\u003e\n\n\u003ctemplate\u003e\n\t\u003cVueUnity :unity=\"unityContext\" width=\"800\" height=\"600\" /\u003e\n\u003c/template\u003e\n```\n\n\u003c/details\u003e\n\n## API\n\n### Constructor\n\n```typescript\nnew UnityWebgl(canvas: HTMLCanvasElement | string, config?:UnityConfig)\n\n// or\n\nconst unityContext = new UnityWebgl(config: UnityConfig)\nunityContext.render(canvas: HTMLCanvasElement | string)\n```\n\n- `canvas` : Render Unity canvas elements or selectors.\n- `config` : Initializes the Unity application's configuration items.\n\n#### config\n\nInitializes the Unity application's configuration items.\n\n| Property                     | Type              | Description                                                                                        | Required |\n| ---------------------------- | ----------------- | -------------------------------------------------------------------------------------------------- | -------- |\n| `loaderUrl`                  | string            | Unity resource loader file                                                                         | ✅       |\n| `dataUrl`                    | string            | File containing resource data and scenes                                                           | ✅       |\n| `frameworkUrl`               | string            | File with runtime and plugin code                                                                  | ✅       |\n| `codeUrl`                    | string            | WebAssembly binary file with native code                                                           | ✅       |\n| `streamingAssetsUrl`         | string            | URL for streaming resources                                                                        | Optional |\n| `memoryUrl`                  | string            | URL for generated framework files                                                                  | Optional |\n| `symbolsUrl`                 | string            | URL for generated Unity code files                                                                 | Optional |\n| `workerUrl`                  | string            | URL for generated Unity web worker files                                                           | Optional |\n| `companyName`                | string            | Metadata: Company name                                                                             | Optional |\n| `productName`                | string            | Metadata: Product name                                                                             | Optional |\n| `productVersion`             | string            | Metadata: Product version                                                                          | Optional |\n| `webglContextAttributes`     | object            | WebGL rendering context options. @see[WebGLRenderingContext][webglContextAttributes-url]           | Optional |\n| `devicePixelRatio`           | number            | Canvas device pixel ratio. @see[devicePixelRatio][devicePixelRatio-url]                            | Optional |\n| `matchWebGLToCanvasSize`     | boolean           | Disable automatic WebGL canvas size sync. @see[matchWebGLToCanvasSize][matchWebGLToCanvasSize-url] | Optional |\n| `autoSyncPersistentDataPath` | boolean           | Enables or disables auto synchronization of the persistent data path.                              | Optional |\n| `disabledCanvasEvents`       | string[]          | Overwrites the default disabled canvas events.                                                     | Optional |\n| `cacheControl`               | `(url) =\u003e string` | The Cache Control API                                                                              | Optional |\n\n[devicePixelRatio-url]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio\n[matchWebGLToCanvasSize-url]: https://issuetracker.unity3d.com/issues/webgl-builds-dont-allow-separate-control-on-canvas-render-buffer-size\n[webglContextAttributes-url]: https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getContextAttributes\n\n### Methods\n\n**Instance methods :**\n\n#### ⭐️ `render(canvas: HTMLCanvasElement | string): void;`\n\nRenders UnityInstance into target html canvas element.\n\n- `canvas` : canvas element\n\n```javascript\nawait unityContext.render('#canvas')\n```\n\n#### ⭐️ `unload(): Promise\u003cvoid\u003e;`\n\nUnload the Unity WebGL instance.\n\n```javascript\nawait unityContext.unload()\n```\n\n#### ⭐️ `sendMessage(objectName: string, methodName: string, value?: any): this;`\n\nSend a message to invoke a public method in the Unity scene.\n\n- `objectName`: Object Name in Unity Scene\n- `methodName`: Unity script method name\n- `value`: Passed value\n\n```javascript\nunityContext.sendMessage('GameObject', 'gameStart', { role: 'Tanya' })\n```\n\n#### `requestPointerLock(): void;`\n\nRequest pointer lock on the Unity canvas.\n\n#### `takeScreenshot(dataType?: string, quality?: any): string | undefined;`\n\nCapture a screenshot of the Unity canvas.\n\n- `dataType`: Type of image data\n- `quality`: Image quality\n\n```javascript\nconst screenshot = unityContext.takeScreenshot('image/jpeg', 0.92)\n```\n\n#### `setFullscreen(enabled: boolean): void;`\n\nToggle fullscreen mode.\n\n```javascript\nunityContext.setFullscreen(true)\n```\n\n**Event methods :**\n\n#### `on(name: string, listener: EventListener, options?: { once?: boolean }): this;`\n\nRegister for listening events.\n\n```javascript\nunityContext.on('progress', (progress) =\u003e {\n\tconsole.log('Progress:', progress)\n})\n```\n\n#### `off(name: string, listener?: EventListener): this;`\n\nRemove event listener.\n\n```javascript\nunityContext.off('progress', listener)\n```\n\n**Unity Communication methods :**\n\n#### ⭐️ `addUnityListener(name: string, listener: EventListener, options?: { once?: boolean }): this;`\n\nRegister a specific listener for Unity to call.\n\n```javascript\nunityContext.addUnityListener('GameStarted', (level) =\u003e {\n\tconsole.log('Game started at level:', level)\n})\n\n// then call it in Unity\nwindow.dispatchUnityEvent('GameStarted', 3)\n```\n\n#### `removeUnityListener(name: string, listener?: EventListener): this;`\n\nRemove registered listeners.\n\n```javascript\nunityContext.removeUnityListener('GameStarted', listener)\n```\n\n### ⭐️ `window.dispatchUnityEvent(name: string, ...args: any[])`\n\nThe way to dispatch a registered listener on the Unity side. (Calling JS methods in unity)\n\n```javascript\nwindow.dispatchUnityEvent('GameStarted', 3)\n```\n\n### Events\n\n| Event Name      | Description                                       |\n| --------------- | ------------------------------------------------- |\n| `beforeMount`   | Before rendering UnityInstance to Canvas Element. |\n| `mounted`       | After rendering UnityInstance to Canvas Element.  |\n| `beforeUnmount` | Before UnityInstance unload                       |\n| `unmounted`     | After UnityInstance unload                        |\n| `progress`      | Unity resource loading progress                   |\n| `error`         | Error events                                      |\n| `debug`         | Debug messages from Unity                         |\n\n## Unity-JavaScript Communication\n\n- [Unity Docs: Interaction with browser scripting](https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html)\n\n### 1. Call Unity script functions from JavaScript\n\n```javascript\nconst unityContext = new UnityWebgl()\n\n/**\n * @param {string} objectName Name of an object in your scene.\n * @param {string} methodName Public method name.\n * @param {any} value Passed value.\n */\nunityContext.sendMessage('GameObject', 'StartGame', { role: 'Tanya' })\n```\n\n### 2. Call JavaScript functions from Unity scripts\n\n1. First register the listener for Unity to call via `addUnityListener` on the web side.\n\n```javascript\nunityContext.addUnityListener('gameStart', (level) =\u003e {\n\tconsole.log('Game started at level:', level)\n})\n```\n\n2. Add the registered `gameStart` method to your Unity project.\n\n```javascript\n// javascript_extend.jslib\nmergeInto(LibraryManager.library, {\n\tHello: function () {\n\t\twindow.alert('Hello, world!')\n\t},\n\n\tGameStart: function (level) {\n\t\t//window.alert(UTF8ToString(str));\n\t\twindow.dispatchUnityEvent('gameStart', UTF8ToString(level))\n\t},\n})\n```\n\n3. Call these functions in unity's `C#` scripts:\n\n```csharp\nusing UnityEngine;\nusing System.Runtime.InteropServices;\n\npublic class WebGLPluginJS : MonoBehaviour\n{\n    [DllImport(\"__Internal\")]\n    public static extern void Hello();\n\n    [DllImport(\"__Internal\")]\n    public static extern void GameStart(string level);\n\n    void Start()\n    {\n        Hello();\n        GameStart(\"2\");\n    }\n}\n```\n\n## Issues\n\n- [Keyboard Input and Focus Handling](https://docs.unity3d.com/Manual/webgl-input.html)\n- [Debug and troubleshoot Web builds](https://docs.unity3d.com/Manual/webgl-debugging.html)\n- [Web performance considerations](https://docs.unity3d.com/Manual/webgl-performance.html)\n\n## Contributing\n\nContributions are welcome! Please submit a [Pull Request](https://github.com/Marinerer/unity-webgl/pulls).\n\n## License\n\nApache-2.0 License\n\n## Support\n\nFor issues or questions, please file an issue on the [GitHub repository](https://github.com/Marinerer/unity-webgl).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarinerer%2Funity-webgl","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmarinerer%2Funity-webgl","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarinerer%2Funity-webgl/lists"}