Easily getting variable values from WebGL in Browser

I’m developing some 3D interactions in Unity, and they will be embedded in a webpage which will have other interactive components. I’m going to need to communicate between these other components, and I’m wondering if there’s an easy way to return a value from Unity into JS variables in the browser.

I know I can use SendMessage() to call functions in Unity from external JS, but can I return values from these calls?

I don’t know how to efficiently do this, so the solution I’m thinking of right now looks like this:

Browser:

   var health;
   var exp;
        
        function GetHealth(){
            SendMessage("Player", "GetHealth");
        }
        
        function ReturnValue(varName, val){
           if(varName == "health"){
              health = val;
           }
    
       if(varName == "exp"){
              exp = val;
           }

        //etc.

        }

Unity:

public void GetHealth(){
    Application.ExternalCall("ReturnValue", "health", health); 
}

This is a really ugly solution that would be ripe with problems. Ideally, I’d like to do something like

Browser:

function GetHealth(){
   return SendMessage("Player", "GetHealth");
}

Unity:

public int GetHealth(){
   return health;
}

Any ideas?

i'm also interested in doing this.

Many times

2 Answers

2

this thread in the forums seems pretty relevant.

edit actually it provides a demo of the requested functionality, plus an approach w/ significantly lower runtime overhead than SendMessage, altho it’s only significant if you’re calling into C# several thousands of times per frame, imo.

In the past we had methods like Application.ExternalEval or Application.ExternalCall. However it seems they got deprecated. Instead you should use a “jslib” plugin and use external method definitions in C#. According to the “AddNumbers” example you should be able to return values.