Search code examples
javascriptc#unity-game-enginefrontendunity-webgl

unity webgl and browser javascript communication


So i have this problem with communicating between browser and unity webgl, basically what i want to do is generate objects in unity's scene with javascript code from the view the webgl is being played. In other words, view will have javascript code to create game objects after the scene loaded, not sure if this is possible yet.

i've read the unity documentation but i haven't found an example of how to implement the code shown there or if it's what i'm looking for.

https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html this is what i have been reading, specially the code visibility part, but since i've never worked with frontend that much i'm a bit clueless.


Solution

  • What you can do is to send messages to Unity inside your Javascript code but you'll let Unity do the dirty work about instantiating objects.

    This is an example that I just made:

    First you create a C# script that spawns your object/prefab, like this:

    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class MyObjectSpawner : MonoBehaviour {
        public Transform Prefab;
    
        public void Spawn(string data) {
            var instance = Instantiate(Prefab);
    
            // do what you like with your instantiated object and the data from the javascript here    
        }
    }
    

    Now you create an object inside the scene and attach this script to it. Keep attention about the name you give to the Game Object you just created, this will be important in the next step. For now, let's say we named it "MyGameObject".

    The last step is your javascript inside the game page container. For this example, I've created a button and when it's clicked, the spawnUnityObject() method is called. Like this:

    HTML:

    <button type="button" onclick="spawnUnityObject()">Press me</button>
    

    Javascript:

    function spawnUnityObject() {
        // game object in the scene, method name, method parameter
        SendMessage('MyGameObject', 'Spawn', 'Super string');
    }
    

    The result will be: when you click the "Press me" button inside the html, the game will spawn an object and you can use the "Super string" as a data inside the Spawn() method.

    I hope this helps you. Let me know if you need more details.