Search Unity

Webgl javascript interop: return object

Discussion in 'Scripting' started by karmatha, Jun 19, 2020.

  1. karmatha

    karmatha

    Joined:
    Aug 25, 2012
    Posts:
    50
    I'm trying to setup a communications layer between my Webgl unity build and javascript on the page that contains it. I've followed the instructions on

    https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html

    and that works. However, what I want to do is call a js function on my page that returns a (js) object and serialize that into C#. Sorta like this:

    (javscript)
    Code (JavaScript):
    1. function gameLoaded() {
    2.    return {
    3.       progress: 3,
    4.       mistakes: 5
    5.    }
    6. }

    (c#)
    Code (CSharp):
    1. [Serializable]
    2. struct GameData {
    3.   public int progress;
    4.   public int mistakes;
    5. }
    6.  
    7. [DllImport("__Internal")]
    8. private static extern GameData GameLoaded();
    9.  
    10. public Start() {
    11.    GameData data = GameLoaded();
    12.    print(data.progress); // should print '3'
    13. }
    (javscript)
    Code (JavaScript):
    1. (.jslib)
    2. mergeInto(LibraryManager.library, {
    3.   GameLoaded: function() {
    4.     return window.gameLoaded()
    5.   }
    6. }



    How would I go about doing this?
     
  2. karmatha

    karmatha

    Joined:
    Aug 25, 2012
    Posts:
    50
    Okay I figured something out. On the js side I call `JSON.stringify(object)` and then in C# I take that string and run it through JsonUtility.FromJson<GameData>(result);

    Great success.
     
    mdrunk and PraetorBlue like this.
  3. mdrunk

    mdrunk

    Joined:
    Apr 26, 2014
    Posts:
    11
    still the best option.