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

时间:2018-02-21 14:32:43

标签: javascript unity3d unity-webgl

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

3 个答案:

答案 0 :(得分:2)

我找到了一个适合我的解决方案。 WebGL构建的 Build 文件夹中有一个JavaScript文件UnityProgress.js。在里面你可以找到一个变量progress,它将在加载/下载进度完成后设置为1.0。您可以将代码放在底部的if语句后面运行您的JavaScript代码(不要忘记括号^^)。 但是 Unity App 需要启动一些初始化时间。所以你可能需要设置延迟时间。对我来说2500 ms运作良好。

 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);

    }
}

答案 1 :(得分:1)

我使用不同的方法。这特别有用,因为您可以在自己希望的Unity代码的任何部分定义回调,即您可以对异步事件做出反应。

bool

<T, bool>

答案 2 :(得分:1)

如果您正在考虑使用前端框架,则可能需要研究我制作的该库。它增加了网页和Unity内容之间双向通信的功能。要将Unity内容中的消息发送回网页,您可以创建JavaScript侦听器,该侦听器可以从CSharp代码触发,甚至可以传递数据。

// 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文件来绑定通信。现在,任何JSLib文件中的ReactUnityWebGL对象中都可以使用已在React中注册的侦听器。现在,您可以创建一个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);
  }
});

最后,在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);
  }
}
相关问题