首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Unity 3D WebGL:在应用程序已加载并准备就绪后运行Javascript代码

Unity 3D WebGL:在应用程序已加载并准备就绪后运行Javascript代码
EN

Stack Overflow用户
提问于 2018-02-21 22:32:43
回答 1查看 4.8K关注 0票数 5

当Unity WebGL应用程序完成加载并准备使用时,我如何检查或接收消息?我想要的是在WebGL应用程序准备好之后运行我的WebGL界面的JavaScript函数。

EN

回答 1

Stack Overflow用户

发布于 2018-11-03 04:58:36

如果你正在研究使用前端框架,你可能想看看我做的这个库。它增加了在你的网页和Unity内容之间双向交流的功能。要将消息从Unity内容发送回网页,您可以创建可从CSharp代码触发的JavaScript侦听器,甚至传递数据。

代码语言: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...

});

为了触发我们刚刚创建的事件,您必须创建一个JSLib文件来绑定通信。在React中注册的侦听器现在可以在任何JSLib文件的ReactUnityWebGL对象中使用。您现在可以创建一个JSLib文件并开始使用。我们将在以下目录中创建一个新的JSLib文件。Assets/Plugins/WebGL/MyPlugin.jslb。

代码语言:javascript
复制
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);
  }
});

最后,在CSharp代码中触发事件。我们必须导入JSLib,如下所示。

代码语言:javascript
复制
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);
  }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48908485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档