Search code examples
javascriptunity-game-engineunity-webgl

Send message from Browser to Unity3D


I am trying to send a message to my Unity3D WebGl app.

The controller of my GameObject "Player" looks basically like this:

public class color : MonoBehaviour {

    void Start ()
    {
        gameObject.GetComponent<Renderer>().material.color = Color.red;
    }

    public void green(string s)
    {
        gameObject.GetComponent<Renderer>().material.color = Color.green;
    }
} 

and my Javascript method like this:

function SaySomethingToUnity() {
    SendMessage("Player", "green", "teeeext");
}

But when I call it nothing happens. What am I doing wrong?


Solution

  • Decided to post the comment answer as the answer for people that will have this problem in the future.

    The page must finish loading before calling any function from Unity or else it won't work. When Unity is not yet done loading, the Objects that you want to send message to does not exist. Error will be thrown because of this or it will silently fail if Exception is disabled. So you must wait for some time before calling Unity function from Unity.