leodecm3 / GIT_20220207_WebGlCommunication

Home Page:https://leodecm3.github.io/GIT_20220207_WebGlCommunication/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

WebGL Communication

A simple example of Javascript sending information to the Unity C#

Installation

Unity version 2021.2.10f1

Preview

30 fps gifs, showcasing communication between Javascript and Unity:


Steps

  1. Open the WebGL template, and modify
createUnityInstance(document.querySelector("#unity-canvas"), {

to

var gameInstance = createUnityInstance(document.querySelector("#unity-canvas"), {

  1. 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!


  1. Inside the HTML template create a simple button
<div  class="key" onclick="CommunicationFunction('W')">

  1. At Unity create a Gameobject called HTML_Com

  1. Attach HTML_Com an script with an public Function
public void InputFromJavascript(string _inputtedString) { ... }




External:

For the environment I used the Starter asset Oficial from Unity:

  • Starter Assets - First Person Character Controller

=> https://assetstore.unity.com/packages/essentials/starter-assets-first-person-character-controller-196525

About

https://leodecm3.github.io/GIT_20220207_WebGlCommunication/


Languages

Language:ShaderLab 63.8%Language:C# 21.3%Language:HLSL 11.1%Language:HTML 3.8%