Call JavaScript functions from Unity C# scripts
Call functions from your JavaScript plug-in or browser in your Unity project.
Read time 6 minutesLast updated 13 days ago
You can use functions from your JavaScript plug-ins in your Unity C# code. It can be useful to use JavaScript code in Unity because you might need to communicate with other elements on your web page or Web APIs.
To learn about the file types and how to set up a JavaScript plug-in for interaction with Unity scripts, refer to Set up your JavaScript plug-in. To learn how to interact with C/C++/C# plug-ins instead, refer to Call C/C++/C# functions from Unity C# scripts.
Topic | Description |
|---|---|
| Pass different variables from JavaScript to Unity | Tips on how to pass different variables between Unity and JavaScript. |
| Execute build code in its own scope | Tips on how to improve visibility of code between Unity and JavaScript. |
| Example Unity C# code that calls JavaScript functions | This example code shows how to call JavaScript functions in Unity. |
| Use Unity plug-ins as a reference | Shows a list of plug-ins included with Unity you can use as a reference. |
Pass different variables from JavaScript to Unity
To integrate JavaScript with Unity, you need efficient communication between the two. Use the following tips on how to pass various types of data from JavaScript to Unity.
Numeric types
You can pass simple numeric types to JavaScript in function parameters without converting them.
For example, this function in JavaScript:
AddNumbers: function (x, y) { return x + y; },
accepts the integer values from C# without conversions:
int result = AddNumbers(5, 7);
You can pass other data types as a pointer in the Emscripten heap. The Emscripten heap is just a large array in JavaScript memory.
Strings
To convert a string to a JavaScript string, use the helper function.
UTF8ToStringvar stringMessage = UTF8ToString("Hello World");
To return a string value, call to allocate some memory and the helper function to write a JavaScript string to the memory. If the string is a return value, then the IL2CPP runtime automatically frees up the memory for you.
_mallocstringToUTF8var returnStr = "Hello World"; var bufferSize = lengthBytesUTF8(returnStr) + 1; var buffer = _malloc(bufferSize); stringToUTF8(returnStr, buffer, bufferSize);
Arrays
For arrays of primitive types, Emscripten provides different into its heap for different sizes of integer, unsigned integer, or floating-point representations of memory: , , , , , , , , , .
ArrayBufferViewsHEAP8HEAPU8HEAP16HEAPU16HEAP32HEAPU32HEAPF32HEAP64HEAPU64HEAPF64To convert a pointer to the array index, use the macro . The parameter is the name of the pointer parameter as a string. The parameter depends on the heap view you're using. Use the following values:
{{{ ptrToIdx(ptr, accessShift) }}}ptraccessShiftMemory object | accessShift |
|---|---|
| HEAP8, HEAPU8 | 0 |
| HEAP16, HEAPU16 | 1 |
| HEAP32, HEAPU32, HEAPF32 | 2 |
| HEAP64, HEAPU64, HEAPF64 | 3 |
The following function loops through the array and outputs the values at each index.
HEAPF32PrintFloatArray: function (array, size) { for(var i = 0; i < size; i++) console.log(HEAPF32[{{{ ptrToIdx('array', 2) }}} + i]);},
Support 64-bit WebAssembly in JavaScript plug-ins
To support 64-bit WebAssembly in JavaScript plug-ins, use for pointer and size parameters in C#, and use an appropriate pointer type (, such as or ) together with in C++.
IntPtrT*void*float*size_tIf you use proxying, configure the appropriate function signature. Use for pointer and length parameters, as described in the Emscripten documentation.
pThe following examples demonstrate how to declare pointer and size parameters in JavaScript plug-ins, C# bindings, and C/C++ bindings so they remain compatible with 64-bit WebAssembly.
Plug-in code:
PointerExample__sig: "vpp",PointerExample__proxy: "sync",PointerExample: function (ptr, size) { // ...}
C# bindings:
using UnityEngine;using System.Runtime.InteropServices;public class NewBehaviourScript : MonoBehaviour { [DllImport("__Internal")] private static extern void PointerExample(IntPtr ptr, IntPtr size);}
C/C++ bindings:
extern "C"{ void PointerExample(void* ptr, size_t size);}
If you need to write specialized JavaScript for 64-bit WebAssembly, use the Emscripten macro :
MEMORY64Example: function(ptr, size) {#if MEMORY64 // 64-bit code goes here#else // 32-bit code goes here#endif}
Textures
To access a texture in WebGL, Emscripten provides the array which maps native texture IDs from Unity to WebGL texture objects. You can call WebGL functions on Emscripten’s WebGL context, .
GL.texturesGLctxFor example, the following function binds a WebGL texture from the GL texture array to a 2D texture.
BindWebGLTexture: function (texture) { GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]); },
Execute build code in its own scope
It is recommended that you execute all build code in its own scope. If you have your code in its own scope, you can embed your content on a page without causing conflicts with the embedding page code, and you can embed more than one build on the same page.
Code in .jslib plug-ins
If you have all your JavaScript code in the form of plug-ins inside your project, then this JavaScript code will run inside the same scope as the compiled build and your code should work the same way as in previous versions of Unity. Some of the objects and functions directly visible from the JavaScript plug-in code include:
.jslibModuleSendMessageHEAP8ccall
Call JavaScript functions from global scope
If you want to call the internal JavaScript functions from the global scope of the embedded page, in your Web template , you must use the variable.
index.htmlunityInstanceUse after the Unity engine instantiation succeeds, for example:
unityInstancevar MyGameInstance = null; script.onload = () => { createUnityInstance(canvas, config, (progress) => { /*...*/ }).then((unityInstance) => { MyGameInstance = unityInstance;
Then, you can use to send a message to the build, or use to access the build module object.
MyGameInstance.SendMessage()MyGameInstance.ModuleExample Unity C# code that calls JavaScript functions
The following JavaScript code creates a function named . For this example, use this code in your JavaScript plug-in so you can call it in your Unity C# scripts.
HellomergeInto(LibraryManager.library, { Hello: function () { window.alert("Hello, world!"); },});
Then, use this C# code in your Unity project to call the function from your JavaScript code:
Hellousing UnityEngine;using System.Runtime.InteropServices;public class NewBehaviourScript : MonoBehaviour { [DllImport("__Internal")] private static extern void Hello(); void Start() { Hello(); }}
For a larger code example with varied function types, refer to Code examples: Call JavaScript and C/C++/C# functions in Unity.
Use Unity plug-ins as a reference
There are several plug-ins in the Unity installation folder that you can use as reference:
-
PlaybackEngines/WebGLSupport/BuildTools/lib -
PlaybackEngines/WebGLSupport/BuildTools/Emscripten/src/library*