频道
bg

Unity webgl

coding七月 11, 20211mins
Unity Frontend

基础H1

WebGL:与浏览器脚本交互 - Unity 手册

从 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.jsx
import 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.jsx
import 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.jslib
mergeInto(LibraryManager.library, {
GameOver: function (userName, score) {
ReactUnityWebGL.GameOver(Pointer_stringify(userName), score);
},
});
/// File: GameController.cs
using 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
}
}

评论


新的评论

匹配您的Gravatar头像

Joen Yu

@2022 JoenYu, all rights reserved. Made with love.