简体   繁体   English

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

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

`I have a Unity 3D Project where i can drive around with a forklift and i want to add features like picking stuff up, putting it down and colorize materials. `我有一个 Unity 3D 项目,我可以在其中使用叉车四处行驶,我想添加一些功能,例如拾取、放下和为材料着色。 But I have a problem with connecting the buttons (which I made in the index.html, which is generated when i run my project with webgl) with my unity code.但是我在使用我的统一代码连接按钮(我在 index.html 中创建,它是在我使用 webgl 运行我的项目时生成的)时遇到问题。 The webgl page looks like this: my project webgl 页面如下所示:我的项目

I already tried it with UnityLoader.instantiate but it does not work for me i get the following error: UnityLoader - error我已经用 UnityLoader.instantiate 试过了,但它对我不起作用我收到以下错误: UnityLoader - error

Here is the script from my Index.html `这是我的 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应该从 UnityLoader 调用的 function

The way via the UnityLoader afaik is from very early Unity WebGL versions.通过UnityLoader afaik 的方式来自非常早期的 Unity WebGL 版本。


You want to store the result of the createUnityInstance within the then block and then use it later like您想要将createUnityInstance的结果存储在then块中,然后稍后使用它

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

then you can later on use it and do然后你可以稍后使用它并做

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

However you can not do this in the current spot in the script initilazation level.但是,您不能在脚本启动级别的当前位置执行此操作。 You will have to wait until that then block was actually called and then do it for your button eg您将不得不等到then块被实际调用,然后为您的按钮执行它,例如

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

...

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

As a more complex alternative though you can implement a plugin and let the c# part inject a callback into it you can later call and once your project gets more complex you might want to go with that rather.作为一个更复杂的替代方案,尽管您可以实现一个插件并让 c# 部分向其中注入一个回调,您可以稍后调用,一旦您的项目变得更复杂,您可能想要 go 而不是。

Eg have a MyFancyPlugin.jslib例如有一个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);

and on your button do eg然后在你的按钮上做例如

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

and then in c# have something like eg然后在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}");
    }
}

where something has to call必须打电话的地方

MyFancyPlugin.Initialize();

of course当然

暂无
暂无

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

相关问题 如何将index.html中的内容放入我的view.html? - How can I put content from my index.html into my view.html? 如何从index.html加载我的Aurelia应用,该索引与应用的其余部分不在同一文件夹中? - How can I load my Aurelia app from an index.html which is not located in the same folder as the rest of the application? 如何将来自github的现有扩展包含到我的主要index.html代码中? - How to include an already existing extension from github into my main index.html code? 如何链接回index.html上的选项卡? - How do I link back to a tab on my index.html? 我的Javascript Ajax请求可在Phonegap index.html中使用,但不能在其他任何页面中使用,如何解决此问题? - My Javascript Ajax request works in Phonegap index.html but not in any other pages, how can I fix this? 如何使用gulp-inject将文件的内容插入到index.html中? - How can I insert the contents of a file in my index.html with gulp-inject? 如何在 React 的 index.html 文件中正确包含 css 文件? - How can I properly include a css file in my index.html file in React? 我如何在没有Index.html或.php的情况下将WebApplication文件运行到服务器? - How can I run my WebApplication files to the server without an Index.html or.php? 如何从index.html获取我的js文件的所有src? - How can to get all srcs for my js file from index.html? 我怎样才能通过js保护我的index.html网站所以我只能在我的电脑上打开它? - how can i protect my index.html website by js so i can only open it on my pc?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM