Unity WebGL SendMessage 到 Unity 函数错误对象 InGameCanvas/CoilValue 未找到

Unity WebGL SendMessage to Unity function error object InGameCanvas/CoilValue not found

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

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 库文件中调用统一。

首先,从 index.html 底部删除这一行 <script src="meta_monetization_handler.js"></script>

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

将其保存到名为 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
   }
}

希望对您有所帮助!

我更改了 canvas 以匹配相机视图。很久以后我还注意到 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);