Pat*_*ter 5 javascript unity-game-engine unity-webgl
当 Unity WebGL 应用程序完成加载并准备好使用时,如何检查或接收消息?我想要的是在 WebGL 应用程序准备好后运行我的 Webinterface 的 JavaScript 函数。
小智 6
如果您正在考虑使用前端框架,您可能需要查看我制作的这个库。它为您的网页和 Unity 内容之间的双向通信添加了功能。要将消息从您的 Unity 内容发送回网页,您可以创建可以从您的 CSharp 代码触发的 JavaScript 侦听器,甚至传递数据。
// Create a new Unity Content object (using the library)
this.unityContent = new UnityContent(
"MyGame/Build.json",
"MyGame/UnityLoader.js" );
// Then add a new listener to the object.
this.unityContent.on("GameOver", score => {
// Do somehting...
});
Run Code Online (Sandbox Code Playgroud)
为了触发我们刚刚创建的事件,您必须创建一个 JSLib 文件来绑定通信。在 React 中注册的侦听器现在可以在任何 JSLib 文件的 ReactUnityWebGL 对象中使用。您现在可以创建一个 JSLib 文件并开始使用。我们将在以下目录中创建一个新的 JSLib 文件。资产/插件/WebGL/MyPlugin.jslib。
mergeInto(LibraryManager.library, {
// Create a new function with the same name as
// the event listeners name and make sure the
// parameters match as well.
GameOver: function(score) {
// Within the function we're going to trigger
// the event within the ReactUnityWebGL object
// which is exposed by the library to the window.
ReactUnityWebGL.GameOver(score);
}
});
Run Code Online (Sandbox Code Playgroud)
最后,在您的 CSharp 代码中触发事件。我们必须按如下方式导入 JSLib。
using UnityEngine;
public class GameController : MonoBehaviour {
// Import the JSLib as following. Make sure the
// names match with the JSLib file we've just created.
[DllImport("__Internal")]
private static extern void GameOver (int score);
// Then create a function that is going to trigger
// the imported function from our JSLib.
public void GameOver (int score) {
GameOver (score);
}
}
Run Code Online (Sandbox Code Playgroud)
我找到了一个适合我的解决方案。WebGL 构建的BuildUnityProgress.js文件夹中有一个 JavaScript 文件。在里面你可以找到一个变量,在加载/下载进度完成后,该变量将被设置为1.0。您可以将代码放在底部的 if 语句之后来运行 JavaScript 代码(不要忘记括号^^)。但Unity App启动需要一些初始化时间。所以你可能必须设置一个延迟时间。对我来说,女士工作得很好。progress2500
function UnityProgress(gameInstance, progress) {
...
if (progress == 1.0) {
gameInstance.logo.style.display = gameInstance.progress.style.display = "none";
// call of my function:
console.log("#### WebGL is ready now ####");
setTimeout(function() {
myFunction();
}, 2500);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4345 次 |
| 最近记录: |