代码之家  ›  专栏  ›  技术社区  ›  hal

如何从Unity内部检索页面信息?

  •  1
  • hal  · 技术社区  · 6 年前

    我需要在两个方向上与页面进行统一的网络组件通信。

    这是我如何从第页执行Unity函数的方法:

    <script>
        var gameInstance = UnityLoader.instantiate("gameContainer", "https://propper_url/Build/_Builds.json", {onProgress: UnityProgress});
    
        function unityObjectFun(index)
        {
            gameInstance.SendMessage ("ObjectInstance", "objectFunctionName", index);
        }
    </script>
    
    <a onclick="unityObjectFun(1)">invoke</a>
    
    <div class="webgl-content">
        <div id="gameContainer" myValue="need this to read from Unity"></div>
    </div>
    

    但我怎么能反过来呢。是否可以从Unity中检索myValue。

    或者,是否可以通知页面Unity加载了场景并开始播放,以便我可以将myValue发送给它?

    1 回复  |  直到 6 年前
        1
  •  1
  •   hal    6 年前

    要在Unity WebAssembly的页面上执行任何JavaScript代码,需要两件事:

    1. 将Javascript代码创建为插件。
    2. 在Unity脚本中导入代码。

    https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html .

    mergeInto(LibraryManager.library, {
        Hello: function () {
            window.alert("Hello, world!");
        },
        HelloReturn: function () {
            return "Hello, world!";
        }
    }
    

    要使用它,需要导入:

    using System.Runtime.InteropServices;
    
    public class NewBehaviourScript : MonoBehaviour {
    
        [DllImport("__Internal")]
        private static extern void Hello();
    
        [DllImport("__Internal")]
        private static extern string HelloReturn();
    
        void Start() {
            Hello();
            Debug.log(HelloReturn());
        }
    }