DEV Community

Cover image for How to call javascript functions from Unity C# class in unity?
Imai Jiro
Imai Jiro

Posted on

How to call javascript functions from Unity C# class in unity?

Calling JavaScript functions from a Unity C# class in Unity can be achieved when you're working with a WebGL build, where Unity allows interaction between the Unity environment and the surrounding browser JavaScript. Below are the steps to do this:

1. Using ExternalEval (Deprecated)

In older versions of Unity, you could use Application.ExternalEval. However, this is deprecated, and you should use Application.ExternalCall or Application.ExternalEval.

2. Using Application.ExternalCall (Deprecated)

This was also deprecated but worked similarly to ExternalEval.

3. Using JavaScriptInterface (Recommended)

Unity introduced a more robust way to interact with JavaScript using the JavaScriptInterface for WebGL. The approach is to define a JavaScript function in your web page and call it from your Unity C# script.

4. Using WebGLPlugin (Recommended)

This is the most current and preferred method. Unity provides a way to call JavaScript functions directly from C# using WebGL plugins.

Step-by-Step Guide:

1. Create Your JavaScript File:

First, create a JavaScript file with the functions you want to call. For example, let's create a file called unityFunctions.js:

function ShowAlert(message) {
    alert(message);
}

function AddNumbers(a, b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

2. Include the JavaScript in Your WebGL Template:

When building for WebGL, include this JavaScript file in your WebGL template or HTML file. Make sure that the JavaScript file is correctly referenced:

<script src="unityFunctions.js"></script>
Enter fullscreen mode Exit fullscreen mode

3. Create a C# Wrapper in Unity:

In Unity, create a C# class that will call these JavaScript functions:

using UnityEngine;
using System.Runtime.InteropServices;

public class WebGLInteraction : MonoBehaviour
{
    // Import the JavaScript functions using DLLImport
    [DllImport("__Internal")]
    private static extern void ShowAlert(string message);

    [DllImport("__Internal")]
    private static extern int AddNumbers(int a, int b);

    // Method to call the JavaScript ShowAlert function
    public void CallShowAlert()
    {
        ShowAlert("Hello from Unity!");
    }

    // Method to call the JavaScript AddNumbers function
    public void CallAddNumbers()
    {
        int result = AddNumbers(5, 3);
        Debug.Log("Result from JavaScript: " + result);
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Call the Functions from Your C# Script:

You can now call these methods in your Unity scripts just like any other C# method:

public class GameManager : MonoBehaviour
{
    void Start()
    {
        WebGLInteraction webGLInteraction = new WebGLInteraction();
        webGLInteraction.CallShowAlert();
        webGLInteraction.CallAddNumbers();
    }
}
Enter fullscreen mode Exit fullscreen mode

Important Notes:

  • Only for WebGL Builds: This method works only in Unity WebGL builds. If you try to call these methods in the Unity editor or in a non-WebGL build, it will throw errors.

  • JavaScript Functions Must Be Global: The JavaScript functions that you want to call from Unity must be globally accessible in the web page where your Unity WebGL content is running.

  • DllImport("__Internal"): This attribute is used to indicate that the methods are external JavaScript functions when targeting WebGL.

Top comments (2)

Collapse
 
james_baron_cea6fdb27c594 profile image
James Baron

Hi Imai Jiro, I am using this to communicate with a webobject in Storyline 360 but any time I add compression to the Unity build I have an error. Any ideas?

Collapse
 
imaijiro profile image
Imai Jiro

It sounds like the issue could be related to how Unity handles WebGL builds with compression, especially when interacting with external web objects like Storyline 360. Compression in WebGL builds can sometimes interfere with the way external JavaScript files or web objects are loaded, leading to errors.

Check Compression Settings: Make sure that the WebGL compression settings match what is supported by the browser and Storyline 360. Unity offers several compression options (e.g., Brotli, Gzip). Try switching between these options (in Player Settings -> Publishing Settings) to see if one works better with Storyline.

Decompress on the Server Side: If you're using compressed builds (e.g., Gzip), ensure that the web server is correctly configured to serve compressed content and decompress it on the client side. Some browsers may fail to load compressed files if the server isn’t set to handle them properly.

Test Without Compression: As a quick test, disable compression (set to "None") and see if the communication between Unity and Storyline 360 works without issues. This will help confirm if compression is the root cause.

Check Browser Console Logs: Open your browser's developer tools (F12) and check for any specific errors in the console when the compressed build is used. This might give more detailed insights into what is going wrong

Review External JavaScript Calls: If possible, ensure that your JavaScript functions in Storyline 360 are accessible globally and aren't being blocked or altered by compression mechanisms