
Unity webgl
coding七月 11, 20211mins
Unity Frontend
基础H1
从 Unity 脚本调用 JavaScript 函数H2
使用jslib定义
jsx
mergeInto(LibraryManager.library, {Hello: function () {window.alert("Hello, world!");},HelloString: function (str) {window.alert(Pointer_stringify(str));},PrintFloatArray: function (array, size) {for(var i = 0; i < size; i++)console.log(HEAPF32[(array >> 2) + i]);},AddNumbers: function (x, y) {return x + y;},StringReturnValueFunction: function () {var returnStr = "bla";var bufferSize = lengthBytesUTF8(returnStr) + 1;var buffer = _malloc(bufferSize);stringToUTF8(returnStr, buffer, bufferSize);return buffer;},BindWebGLTexture: function (texture) {GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]);},});
从 C# 脚本调用这些函数
csharp
using UnityEngine;using System.Runtime.InteropServices;public class NewBehaviourScript : MonoBehaviour {[DllImport("__Internal")]private static extern void Hello();[DllImport("__Internal")]private static extern void HelloString(string str);[DllImport("__Internal")]private static extern void PrintFloatArray(float[] array, int size);[DllImport("__Internal")]private static extern int AddNumbers(int x, int y);[DllImport("__Internal")]private static extern string StringReturnValueFunction();[DllImport("__Internal")]private static extern void BindWebGLTexture(int texture);void Start() {Hello();HelloString("This is a string.");float[] myArray = new float[10];PrintFloatArray(myArray, myArray.Length);int result = AddNumbers(5, 7);Debug.Log(result);Debug.Log(StringReturnValueFunction());var texture = new Texture2D(0, 0, TextureFormat.ARGB32, false);BindWebGLTexture(texture.GetNativeTextureID());}}
从 JavaScript 调用 Unity 脚本函数H2
建议的做法是调用内容中的游戏对象上的方法。如果要从嵌入在项目中的 JavaScript 插件执行调用,可使用以下代码
jsx
unityInstance.SendMessage(objectName, methodName, value);
其中,objectName 是场景中的对象名称;methodName 是当前附加到该对象的脚本中的方法名称;value 可以是字符串、数字,也可为空。例如:
ReactH1
React和Unity通信H2
示例
jsx
// File: App.jsximport React from "react";import Unity, { UnityContext } from "react-unity-webgl";const unityContext = new UnityContext({loaderUrl: "build/myunityapp.loader.js",dataUrl: "build/myunityapp.data",frameworkUrl: "build/myunityapp.framework.js",codeUrl: "build/myunityapp.wasm",});function App() {function spawnEnemies() {unityContext.send("GameController", "SpawnEnemies", 100);}return (<div><button onClick={spawnEnemies}>Spawn a bunch!</button><Unity unityContext={unityContext} /></div>);}
csharp
// File: EnemyController.cs// Attached to GameObject "GameController"public class EnemyController : MonoBehaviour {public void SpawnEnemies (int amount) {Debug.Log ($"Spawning {amount} enemies!");}}
Unity 和 React 通信H2
示例
React订阅
csharp
// File: App.jsximport React, { useState, useEffect } from "react";import Unity, { UnityContext } from "react-unity-webgl";const unityContext = new UnityContext({loaderUrl: "build/myunityapp.loader.js",dataUrl: "build/myunityapp.data",frameworkUrl: "build/myunityapp.framework.js",codeUrl: "build/myunityapp.wasm",});function App() {const [isGameOver, setIsGameOver] = useState(false);const [userName, setUserName] = useState("");const [score, setScore] = useState(0);useEffect(function () {unityContext.on("GameOver", function (userName, score) {setIsGameOver(true);setUserName(userName);setScore(score);});}, []);return (<div>{isGameOver === true && <p>{`Game Over! ${userName} ${score} points`}</p>}<Unity unityContext={unityContext} /></div>);}
Utility发送
csharp
// File: MyPlugin.jslibmergeInto(LibraryManager.library, {GameOver: function (userName, score) {ReactUnityWebGL.GameOver(Pointer_stringify(userName), score);},});/// File: GameController.csusing UnityEngine;using System.Runtime.InteropServices;public class GameController : MonoBehaviour {[DllImport("__Internal")]private static extern void GameOver (string userName, int score);public void SomeMethod () {#if (UNITY_WEBGL == true && UNITY_EDITOR == false)GameOver ("Player1", 100);#endif}}
评论
新的评论
上一篇
前端SPA部署路径
当前端的SPA应用不是部署在域名的根目录下,而是部署在某个context path下时,需要特别注意资源、路由、接口等请求路径。 资源 资源主要指是的 index.html 中引用的webpack bundle、页面的以路径方式引用的图片等静态资源等。 在路由使用hash的路…
下一篇
支持CommonJS 和 ES6模块
一个模块同时要支持 CommonJS 和 ES6 两种格式,也很容易。 如果原始模块是 ES6 格式,那么需要给出一个整体输出接口,比如 export default obj ,使得 CommonJS 可以用 import() 进行加载。 如果原始模块是 CommonJS 格式…
