【问题标题】:Unity WebGL SendMessage to Unity function error object InGameCanvas/CoilValue not foundUnity WebGL SendMessage to Unity function error object InGameCanvas/CoilValue not found
【发布时间】:2019-09-15 16:22:50
【问题描述】:

我一直在尝试使用 JavaScript 从网页向 Unity 函数发送一条消息,但在调用该函数时我继续得到一个未找到的值。 关联的对象是画布的子对象,所以我不确定这是否是一个问题。我尝试了多种方法来实现它

coilScore 是一个浮点数,我只是在传递数字。

我尝试到达子对象。

gameInstance.SendMessage('CoilValue', 'ReceiveCoilScore', coilScore);[![enter image description here][1]][1]
gameInstance.SendMessage('InGameCanvas/CoilValue', 'ReceiveCoilScore', coilScore);
gameInstance.SendMessage('InGameCanvas', 'ReceiveCoilScore', coilScore);
gameInstance.SendMessage('InGameCanvas.CoilValue', 'ReceiveCoilScore', coilScore);


Error: 
SendMessage: object InGameCanvas/CoilValue not found!  a4527c6b-a81a-4c23-8861-f3553ac675c8:8:48803
Type: number Total coilScore: 0.000001401 meta_monetization_handler.js:34:10

编辑

为了清楚起见,我在此行下方添加了其他信息。

index.html 正在调用一个 .js 文件。在该 .js 文件中,我正在解析多个参数,但我想做的一项是将 .js 文件中的消息发送到 Unity。

index.html

<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Moon Run</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
    <script src="TemplateData/UnityProgress.javascript"></script>
    <script src="Build/UnityLoader.js"></script>
    <script>
        var gameInstance = UnityLoader.instantiate("gameContainer", "Build/Moon Run WebGL nonDev.json", {onProgress: UnityProgress});
    </script>
</head>
<body>
<div class="webgl-content">
    <div id="gameContainer" style="width: 1920px; height: 1080px"></div>
</div>
<script src="TemplateData/responsive.javascript"></script>
<script src="meta_monetization_handler.js"></script>
</body>
</html>

meta_monetization_handler.js

   function calcValue(data) {
    return (data.amount * (1 / Math.pow(10, data.assetScale)).toPrecision(data.assetScale)).toPrecision(data.assetScale);
}

if (typeof document.monetization == "undefined") {
    console.log('document.monetization not found :(');
} else {
    var info_div = document.querySelector('body > div > div.validator > div');
    var ilp_element = document.getElementById('ilpEnabled');
    var ilp_raw_init_el = document.getElementById('rawInit');
    var cur_pay_el = document.getElementById('currentPaymentAmt');
    var total_estimate_el = document.getElementById('totalEstimateAmt');
    var latest_json_el = document.getElementById('latestJson');

    document.monetization.addEventListener('monetizationstart', function(event) {
        info_div.style.backgroundColor = "rgba(63, 65, 68, 0.4)";
        ilp_element.innerHTML = "Interledger Enabled! (Meta-Tag)<br><br>:)  Thank You!<br>";
        ilp_raw_init_el.innerHTML = JSON.stringify(event.detail, null, 2).replace('{','').replace('}','');
    });

    document.monetization.addEventListener('monetizationprogress', function(event) {
        if (typeof this.runningTotal == "undefined") {
            this.runningTotal = 0;
        }
        var monetizationAmount = parseFloat(calcValue(event.detail));
        this.runningTotal += monetizationAmount;
        document.monetization.lastEventPayload = event.detail;
        cur_pay_el.innerHTML = "Latest ILP Payment: $" + monetizationAmount;
        total_estimate_el.innerHTML = "Estimated ILP Total: $" + this.runningTotal.toPrecision(4);
        latest_json_el.innerHTML = "Latest ILP Payment Response: " + JSON.stringify(event.detail);

    coilScore = this.runningTotal.toPrecision(4);
    console.log("Type: " + typeof coilScore  + " Total coilScore: " + coilScore );
    gameInstance.SendMessage('CoilValueTextObject', 'ReceiveCoilScore', coilScore);
    });
}

【问题讨论】:

    标签: javascript html unity3d sendmessage unity-webgl


    【解决方案1】:

    我更改了画布以匹配相机视图。很久以后我还注意到 javascript 正在使用 toPrecision(4) 并且我有一个浮动的函数。 toPrecision 将浮点数转换为字符串和字符串以将其用作参数,因此它失败了。

    解决方案:确保我发送的是一个字符串,并且接收端的函数接受一个字符串。

        public void ReceiveCoilScore(float newValue)
        {
            //gameSession.coilScore = newValue;
            //coilScoreText.text = string.Format("{0:N9}", gameSession.GetCoilScore());
            coilScore = newValue;
            coilScoreText.text = string.Format("{0:N9}", coilScore);
        }
    

    将浮点数转换为字符串

        coilScore = this.runningTotal.toPrecision(4);
        console.log("Type: " + typeof coilScore  + " Total coilScore: " + coilScore );
        gameInstance.SendMessage('CoilValueTextObject', 'ReceiveCoilScore', coilScore);
    

    【讨论】:

      【解决方案2】:

      让我们从一个统一的 JavaScript 库文件中调用统一。

      首先,从 index.html 的底部删除这一行 &lt;script src="meta_monetization_handler.js"&gt;&lt;/script&gt;

      现在让我们创建统一的 javascriptLibrary 文件。

      将其保存到名为MetaMonitizationHandler.jslib 的文件或您想要的任何名称但保留扩展名的文件中,并将该文件统一放在项目中名为 Plugins 的任何文件夹中。

      将此格式化的javascript代码添加到文件MetaMonitizationHandler.jslib

      var MetaMonitizationHandler =
      {
          calcValue: function (data)
          {
              return (data.amount * (1 / Math.pow(10, data.assetScale)).toPrecision(data.assetScale)).toPrecision(data.assetScale);
          },
      
          Initialize: function ()
          {
              if (!typeof document.monetization)
              {
                  console.log('document.monetization not found :(');
              }
              else
              {
                  var info_div = document.querySelector('body > div > div.validator > div');
                  var ilp_element = document.getElementById('ilpEnabled');
                  var ilp_raw_init_el = document.getElementById('rawInit');
                  var cur_pay_el = document.getElementById('currentPaymentAmt');
                  var total_estimate_el = document.getElementById('totalEstimateAmt');
                  var latest_json_el = document.getElementById('latestJson');
      
                  document.monetization.addEventListener('monetizationstart', function (event)
                  {
                      info_div.style.backgroundColor = "rgba(63, 65, 68, 0.4)";
                      ilp_element.innerHTML = "Interledger Enabled! (Meta-Tag)<br><br>:)  Thank You!<br>";
                      ilp_raw_init_el.innerHTML = JSON.stringify(event.detail, null, 2).replace('{', '').replace('}', '');
                  });
      
                  document.monetization.addEventListener('monetizationprogress', function (event)
                  {
                      if (!typeof this.runningTotal)
                      {
                          this.runningTotal = 0;
                      }
                      var monetizationAmount = parseFloat(calcValue(event.detail));
                      this.runningTotal += monetizationAmount;
                      document.monetization.lastEventPayload = event.detail;
                      cur_pay_el.innerHTML = "Latest ILP Payment: $" + monetizationAmount;
                      total_estimate_el.innerHTML = "Estimated ILP Total: $" + this.runningTotal.toPrecision(4);
                      latest_json_el.innerHTML = "Latest ILP Payment Response: " + JSON.stringify(event.detail);
      
                      coilScore = this.runningTotal.toPrecision(4);
                      console.log("Type: " + typeof coilScore + " Total coilScore: " + coilScore);
                      gameInstance.SendMessage('CoilValueTextObject', 'ReceiveCoilScore', coilScore);
                  });
              }
          },
      };
      mergeInto(LibraryManager.library, MetaMonitizationHandler);
      

      创建一个名为 MonitizationManager.cs 或您认为合适的任何名称的新 C# 脚本, 从这个脚本中,我们将初始化货币化处理程序。

      using UnityEngine;
      using System.Runtime.InteropServices;
      public class MonitizationManager : MonoBehaviour
      {
         [DllImport("__Internal")]
         static extern void Initialize(); // the function in the javascript which initializes the handles.
      
         private void Start()
         {
      #if !UNITY_EDITOR && UNITY_WEBGL
            Initialize();
      #endif
         }
      }
      

      希望这会有所帮助!

      【讨论】:

      • 这是一个非常好的发现。我将其更改为公开,更改了对象名称以确保它是唯一的,但我仍然遇到相同的错误。 new object name = CoilValueTextObjectscript function now public = public void ReceiveCoilScore(float newValue)SendMessage: object CoilValueTextObject not found!
      • 你用的是什么统一版本?如果是新版本,您需要使用“unityInstance”而不是“gameInstance”,因为在新版本中,Unity 将其 javascript 对象重命名为“unityInstance”。
      • 我使用的是 2019.2,它在 index.html 中显示为 gameInstance。在我的自定义 javascript(单独的文件)中再次创建实例是否有问题,或者我应该尝试使用 index.html 实例从 JS 调用它 gameInstance.SendMessage?
      • 自定义 Javascript 是指 .js 文件还是 .jslib 文件?
      • .js 我编辑了原始帖子,因为它更容易在上面显示而不是尝试在下面解释。
      猜你喜欢
      • 2018-12-13
      • 2022-12-19
      • 2012-05-19
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 2020-04-17
      相关资源
      最近更新 更多