A simple example of Javascript sending information to the Unity C#
Unity version 2021.2.10f1
30 fps gifs, showcasing communication between Javascript and Unity:
- Open the WebGL template, and modify
createUnityInstance(document.querySelector("#unity-canvas"), {
to
var gameInstance = createUnityInstance(document.querySelector("#unity-canvas"), {
- Inside the template, create a function to interact with the C#
function CommunicationFunction(_text) {
gameInstance.then((_unityInstance) => {
_unityInstance.SendMessage('HTML_Com', 'InputFromJavascript', _text);
//_unityInstance.SendMessage(<Game object name>, <Public function at this Game object>, <Variable>);
});
💡 Since unity 2020, the WebGL creates the scene using createUnityInstance , which returns a promise. The only way to interact is by retrieving the promise. A simple unityInstance.SendMessage() do not work anymore!
- Inside the HTML template create a simple button
<div class="key" onclick="CommunicationFunction('W')">
- At Unity create a Gameobject called HTML_Com
- Attach HTML_Com an script with an public Function
public void InputFromJavascript(string _inputtedString) { ... }
For the environment I used the Starter asset Oficial from Unity:
- Starter Assets - First Person Character Controller