如何将Index.html中的按钮连接到Unity Code

rslzwgfq  于 2022-11-20  发布在  其他
关注(0)|答案(1)|浏览(225)

'我有一个Unity 3D项目,我可以开着叉车到处走,我想添加一些功能,比如拾取东西,放下东西,给材料上色。但是我在连接按钮(我在index.html中做的,当我用webgl运行我的项目时生成)和我的Unity代码时遇到了问题。webgl页面看起来像这样:my project
我已经用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>

the function that should be called from the UnityLoader

jyztefdp

jyztefdp1#

通过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#部分注入一个回调到它,你可以稍后调用,一旦你的项目变得更复杂,你可能会想去与它。
例如,具有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();

当然了

相关问题