- Home /
(WebGL) Activate Unity Functions with HTML/Javascript
I know similar questions to this have been asked before, but after following other answers/examples exactly, I still cannot get this working.
According to http://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html you can communicate between the Unity WebGL app itself and the HTML of the container page using
`SendMessage ('MyGameObject', 'MyFunction', 'foobar');`
I have set up an extremely basic scene for testing- a camera, directional light, and a cube with a script "TestFunction" attached to it. TestFunction contains:
using UnityEngine;
using System.Collections;
public class TestFunction : MonoBehaviour {
public bool active;
void Start() {
active = true;
}
// Update is called once per frame
void Update () {
if (active == false)
this.gameObject.SetActive (false);
}
}
My index.html file is the standard Unity WebGL template, along with two additions:
<button onclick="testWebGL()">Test Function</button>
and
<script>
function testWebGL(bool) {
SendMessage ('Cube', 'TestFunction', 'active = false');
console.log('Should be calling a function in Unity')
}
</script>
Upon loading the page on my MAMP web server, waiting for the Unity WebGL application to fully load, and then clicking on my Test Function button, nothing in the app happens (cube should be toggled inactive). The JavaScript console displays:
UnityLoader.js:141 SendMessage: object Cube does not have receiver for function TestFunction!
(index):37 Should be calling a function in Unity
So that shows that the button onClick() event is happening, however I can't seem to get the actual function to work properly. What am I doing wrong / missing here?
Answer by Soraphis · Jun 16, 2016 at 06:00 PM
uhm, i think you confuse component-classes with functions ...
public class TestComponent : MonoBehaviour {
public bool active;
void Start() {
active = true;
}
// Update is called once per frame
void Update () {
if (active == false)
this.gameObject.SetActive (false);
}
void TestFunction(){
active = false;
}
}
call it with:
SendMessage ('Cube', 'TestFunction');
some more information:
the "SendMessage" message method checks every MonoBehaviour for a method with the given name. if such a method exists the method is invoked with the given parameters.
https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html
so there would be no point in using the component name as parameter, and you can't invoke any c# code via a javascript call
Your answer
Follow this Question
Related Questions
Flash to html communication 1 Answer
Unity 5.6 not calling function when called from webpage 1 Answer
Unity Button as HTML Button 1 Answer
External Javascript call in Unity WebGL 1 Answer
Embedded HTML for Unity WebGL build 0 Answers