繁体   English   中英

如何将我的 Index.html 中的按钮连接到我的 Unity 代码

[英]How can i connect Buttons from my Index.html to my Unity Code

`我有一个 Unity 3D 项目,我可以在其中使用叉车四处行驶,我想添加一些功能,例如拾取、放下和为材料着色。 但是我在使用我的统一代码连接按钮(我在 index.html 中创建,它是在我使用 webgl 运行我的项目时生成的)时遇到问题。 webgl 页面如下所示:我的项目

我已经用 UnityLoader.instantiate 试过了,但它对我不起作用我收到以下错误: UnityLoader - error

这是我的 Index.html 中的脚本`

    <script>
      var container = document.querySelector("#unity-container");
      var canvas = document.querySelector("#unity-canvas");
      var loadingBar = document.querySelector("#unity-loading-bar");
      var progressBarFull = document.querySelector("#unity-progress-bar-full");
      var fullscreenButton = document.querySelector("#unity-fullscreen-button");
      var warningBanner = document.querySelector("#unity-warning");

      function unityShowBanner(msg, type) {
        function updateBannerVisibility() {
          warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
        }
        var div = document.createElement('div');
        div.innerHTML = msg;
        warningBanner.appendChild(div);
        if (type == 'error') div.style = 'background: red; padding: 10px;';
        else {
          if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
          setTimeout(function() {
            warningBanner.removeChild(div);``
            updateBannerVisibility();
          }, 5000);
        }
        updateBannerVisibility();
      }

      var buildUrl = "Build";
      var loaderUrl = buildUrl + "/build.loader.js";
      var config = {
        dataUrl: buildUrl + "/build.data",
        frameworkUrl: buildUrl + "/build.framework.js",
        codeUrl: buildUrl + "/build.wasm",
        streamingAssetsUrl: "StreamingAssets",
        companyName: "DefaultCompany",
        productName: "warehouseOnline3D",
        productVersion: "0.1",
        showBanner: unityShowBanner,
      };

  
      if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
        // Mobile device style: fill the whole browser client area with the game canvas:

        var meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
        document.getElementsByTagName('head')[0].appendChild(meta);
        container.className = "unity-mobile";

        // To lower canvas resolution on mobile devices to gain some
        // performance, uncomment the following line:
        // config.devicePixelRatio = 1;

        canvas.style.width = window.innerWidth + 'px';
        canvas.style.height = window.innerHeight + 'px';

        unityShowBanner('WebGL builds are not supported on mobile devices.');
      } else {
        // Desktop style: Render the game canvas in a window that can be maximized to fullscreen:

        canvas.style.width = "960px";
        canvas.style.height = "600px";
      }

      loadingBar.style.display = "block";

      var script = document.createElement("script");
      script.src = loaderUrl;
      script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          progressBarFull.style.width = 100 * progress + "%";
        }).then((unityInstance) => {
          loadingBar.style.display = "none";

          fullscreenButton.onclick = () => {
            unityInstance.SetFullscreen(1);
          };
        }).catch((message) => {
          alert(message);
        });
      };
      document.body.appendChild(script);
      
      var gameInstance = UnityLoader.instantiate("gameContainer", "Build/webgl.json");
      
      gameInstance.SendMessage("Sideloader", "test", "printed from webgl");  
    </script>

应该从 UnityLoader 调用的 function

通过UnityLoader afaik 的方式来自非常早期的 Unity WebGL 版本。


您想要将createUnityInstance的结果存储在then块中,然后稍后使用它

<script>
    let instance = null;
    
    ....
    
    createUnityInstance(canvas, config, (progress) => {
          progressBarFull.style.width = 100 * progress + "%";
        }).then((unityInstance) => {
          instance = unityInstance;
    ...

然后你可以稍后使用它并做

instance.SendMessage("Sideloader", "test", "printed from webgl"); 

但是,您不能在脚本启动级别的当前位置执行此操作。 您将不得不等到then块被实际调用,然后为您的按钮执行它,例如

<button onclick='ButtonClick()'>test</button>

...

function ButtonClick()
{
    if(instance) instance.SendMessage("Sideloader", "test", "printed from webgl"); 
}

作为一个更复杂的替代方案,尽管您可以实现一个插件并让 c# 部分向其中注入一个回调,您可以稍后调用,一旦您的项目变得更复杂,您可能想要 go 而不是。

例如有一个MyFancyPlugin.jslib

var myFancyPlugin = {
{    
    $CallbackPtr : {},

    InitializeJavaScript : function(callbackPtr)
    {
        CallbackPtr = callbackPtr;
    }

    FancyCall : function(value)
    {
        const valueSize = lengthBytesUTF8(value)+1;
        const valueBuffer = _malloc(dataUrlSize);
        stringToUTF8(value, valueBuffer, valueSize);
        Runtime.dynCall("vi", $CallbackPtr, [valueBuffer]);
        free(valueBuffer);
    }
};
autoAddDeps(myFancyPlugin, '$CallbackPtr');
mergInto(LibraryManager.library, myFancyPlugin);

然后在你的按钮上做例如

<button onclick='FancyCall("TEST!")'>test</button>

然后在c#中有类似的东西

public static class MyFancyPlugin
{
    private delegate void Callback(string value);

    [DllImport("__Internal")]
    private static void InitializeJavaScript(Callback callback);

    public static void Initialize()
    {
        InitializeJavaScript(OnCallbackReceived);
    }

    [MonoPInvokeCallback(typeof(Callback))]
    private static void OnCallbackReceived(string value)
    {
        Debug.Log("Received from JavaScript: {value}");
    }
}

必须打电话的地方

MyFancyPlugin.Initialize();

当然

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM