Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

SendMessage from javascript to c

Discussion in 'WebGL' started by nsmith1024, Dec 14, 2016.

  1. nsmith1024

    nsmith1024

    Joined:
    Mar 18, 2014
    Posts:
    869
    Hello,

    I need to send a message from javascript back to my c# code, but i keep getting error.

    in c# i have

    public class OpenClass : MonoBehaviour {

    public void GetMessage(string msg)
    {
    Debug.Log("message="+msg);
    }
    }

    in java script I have
    SendMessage('OpenClass','GetMessage','hello');

    I keep getting error in FireFox console like this:
    sendMessage: object OpenClass not found:


    What should be the first parameter for the sendMessage function in my case?
    Do I need to make OpenClass static? or GetMessage static? I dont understand what it wants!

    I read that the first parameter is the gameObject, but there are no gameobjects in Javascript, so i dont understand what to put for that. Is that the name of the object in the hierarchy window that contains this class?

    Thanks for any help
     
    Last edited: Dec 14, 2016
  2. alexsuvorov

    alexsuvorov

    Unity Technologies

    Joined:
    Nov 15, 2015
    Posts:
    327
    Hello nsmith1024.

    The first parameter should be the name of the game object (from your scene) that your OpenClass script is attached to (and not the name of the script). If you do not have any object that your script is attached to, then you can just create an empty object and attach your script to it. The name of that object should be the first parameter in SendMessage. Note that the very same script can be attached to multiple objects, in which case only the object with the matching name will receive the message.

    P.S. If you are interested in sending a message to a static C# method instead, you might check out the following thread https://forum.unity3d.com/threads/super-fast-javascript-interaction-on-webgl.382734/
     
    Last edited: Dec 14, 2016
    nsmith1024 likes this.