npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

unity-webgl

v4.1.0

Published

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.

Downloads

2,863

Readme

unity-webgl

version codecov release downloads size license

[ English | 中文 ]

unity-webgl 提供了一个简单的解决方案,用于将 Unity WebGL 构建嵌入到 Web 应用程序中,同时为 Unity 和 WebApp 应用之间的双向通信和交互提供 API。

🚨 提醒

v4.x 版本进行了较大更新,API 不兼容 v3.x及之前版本。升级请参考 变更信息

Based on react-unity-webgl

Features

  • 📦 集成简单,无框架限制
  • 📩 支持 WebAppUnity 双向通信和交互
  • ⏰ 全面的事件处理机制
  • 🧲 内置 vue 组件 (vue2/3)

Installation

npm

npm install unity-webgl

browser

https://cdn.jsdelivr.net/npm/unity-webgl/dist/index.min.js

Quick Start

🚨 提醒:
仅在 Unity 实例成功创建后(触发 mounted 事件时)才能进行 Web 应用程序的通信和交互。 建议在页面打开时添加加载进度条。

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实例已创建,可与unity侧进行通信
		unityContext.sendMessage('GameObject', 'ReceiveRole', 'Tanya')
	})

// 供unity 端调用
unityContext.addUnityListener('gameStart', (msg) => {
	console.log('from Unity : ', msg)
})
// window.dispatchUnityEvent('gameStart', '{score: 0}')
<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>

API

Constructor

new UnityWebgl(canvas: HTMLCanvasElement | string, config?:UnityConfig)

// or

const unityContext = new UnityWebgl(config: UnityConfig)
unityContext.create(canvas: HTMLCanvasElement | string)
  • canvas : 渲染Unity的画布元素或选择器。
  • config : 初始化 Unity 应用程序的配置项。

config

初始化 Unity 应用程序的配置项。

| Property | Type | Description | Required | | ------------------------ | ------- | ------------------------------------------------------------------------------------- | -------- | | loaderUrl | string | Unity 资源加载器文件 | ✅ | | dataUrl | string | 包含资源数据和场景的文件 | ✅ | | frameworkUrl | string | 包含运行时和插件代码的文件 | ✅ | | codeUrl | string | 包含原生代码的 WebAssembly 二进制文件 | ✅ | | streamingAssetsUrl | string | 流媒体资源的 URL | 可选 | | memoryUrl | string | 生成的框架文件的 URL | 可选 | | symbolsUrl | string | 生成的 Unity 代码文件的 URL | 可选 | | companyName | string | 元数据:公司名称 | 可选 | | productName | string | 元数据:产品名称 | 可选 | | productVersion | string | 元数据:产品版本 | 可选 | | devicePixelRatio | number | 画布设备像素比率. @seedevicePixelRatio | 可选 | | matchWebGLToCanvasSize | boolean | 禁用 WebGL 画布大小自动同步. @seematchWebGLToCanvasSize | 可选 | | webglContextAttributes | object | WebGL 渲染上下文选项. @seeWebGLRenderingContext | 可选 |

Methods

Instance methods :

⭐️ create(canvas: HTMLCanvasElement | string): void;

在指定画布上创建 Unity WebGL 实例。

  • canvas : canvas画布元素
await unityContext.create('#canvas')

⭐️ unload(): Promise<void>;

卸载 Unity WebGL 实例。

await unityContext.unload()

⭐️ sendMessage(objectName: string, methodName: string, value?: any): this;

Unity 场景中发送消息以调用公共方法。

  • objectName: Unity场景中对象名称
  • methodName: Unity脚本中方法名称
  • value: 传递的值
unityContext.sendMessage('GameObject', 'gameStart', { role: 'Tanya' })

requestPointerLock(): void;

请求锁定 Unity 画布的指针。

takeScreenshot(dataType?: string, quality?: any): string | undefined;

对 Unity 画布进行屏幕截图并返回包含图像数据的数据 URL。

  • dataType: 图像数据的类型
  • quality: 图像的质量
const screenshot = unityContext.takeScreenshot('image/jpeg', 0.92)

setFullscreen(enabled: boolean): void;

切换全屏模式。

unityContext.setFullscreen(true)

Event methods :

on(name: string, listener: EventListener, options?: { once?: boolean }): this;

监听事件。

unityContext.on('progress', (progress) => {
	console.log('Progress:', progress)
})

off(name: string, listener?: EventListener): this;

移除事件监听器。

unityContext.off('progress', listener)

Unity Communication methods :

addUnityListener(name: string, listener: EventListener, options?: { once?: boolean }): this;

注册特定监听器供 Unity 端调用。

unityContext.addUnityListener('GameStarted', (level) => {
	console.log('Game started at level:', level)
})

// then call it in Unity
window.dispatchUnityEvent('GameStarted', 3)

removeUnityListener(name: string, listener?: EventListener): this;

移除注册的监听器。

unityContext.removeUnityListener('GameStarted', listener)

window.dispatchUnityEvent(name: string, ...args: any[])

在 Unity 端派发注册的监听器的方式。(在 unity 中调用 JS 的方法)

window.dispatchUnityEvent('GameStarted', 3)

Events

Unity 实例从创建到销毁过程中触发的事件。

| event name | description | | ----------------------------- | ----------------------- | | beforeMount(unityContext) | 创建 Unity 实例之前触发 | | mounted(unityContext) | 创建 Unity 实例后触发 | | beforeUnmount(unityContext) | 卸载 Unity 实例之前触发 | | unmounted() | 卸载 Unity 实例后触发 | | progress(val: number) | unity 资源加载进度更新 | | error(err: Event\|string) | 发生错误 | | debug(msg: string) | 来自 Unity 的调试消息 |

Unity-JavaScript Communication

1. Call Unity script functions from JavaScript

const unityContext = new UnityWebgl()

/**
 * @param {string} objectName name of an object in your scene.
 * @param {string} methodName public method name.
 * @param {any} value send value.
 */
unityContext.sendMessage('GameObject', 'StartGame', { role: 'Tanya' })

2. Call JavaScript functions from Unity scripts

  1. 首先在 web 端通过 addUnityListener 注册供 Unity 调用的监听器。
unityContext.addUnityListener('gameStart', (level) => {
	console.log('Game started at level:', level)
})
  1. 在Unity项目中,将注册的 gameStart 方法添加到项目中。
// javascript_extend.jslib
mergeInto(LibraryManager.library, {
	Hello: function () {
		window.alert('Hello, world!')
	},

	GameStart: function (level) {
		//window.alert(UTF8ToString(str));
		window.dispatchUnityEvent('gameStart', UTF8ToString(level))
	},
})
  1. C# 脚本中调用这些函数:
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");
    }
}

Issues

License

MIT License

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For issues or questions, please file an issue on the GitHub repository.