snub-fighter
snub-fighter

Reputation: 171

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

I've been trying to send a message from a web page using JavaScript to a Unity function but I continue to get a value not found when calling the function. The object associated is a child object of the canvas so Im not sure that's an issue or not. Ive tried a combination of things to make it

coilScore is a float and I'm simply passing the number across.

My attempts to reach child object.

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

JavaScript snippet to call Unity function Unity Function Game Object Structure

EDIT

Ive added additional information below this line for clarity.

The index.html is calling a .js file. Inside that .js file I am parsing multiple parameters but the one item I am trying to do is send a message from the .js file to 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);
    });
}

Upvotes: 1

Views: 7571

Answers (2)

snub-fighter
snub-fighter

Reputation: 171

I changed the canvas to match the camera view. I also noticed much later that javascript was using toPrecision(4) and I had a function that wa taking a float. toPrecision was conerting the float to a string and string to use that as an argument hence it failed.

Solution : Ensure that what I have been sending was a string and the function on the receiving end takes a string.

    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);
    }

Converting float to string

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

Canvas matches Camera

Upvotes: 1

ChoopTwisk
ChoopTwisk

Reputation: 1334

Let's call unity from a unity javascript library file.

First things first, remove this line <script src="meta_monetization_handler.js"></script> from the bottom of your index.html.

Now lets create our unity javascriptLibrary file.

Save this to a file called MetaMonitizationHandler.jslib or any name you want but keep the extension, and put the file in any folder called Plugins in your project in unity.

Add this formatted javascript code to the file 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);

Create a new C# script named MonitizationManager.cs or any name you see fit, from this script we will initialize the monetization handler.

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
   }
}

Hope this helps!

Upvotes: 0

Related Questions