When building content for the web, you might need to communicate with other elements on your web page. Or you might want to implement functionality using Web APIs which Unity doesn’t expose by default. In both cases, you need to directly interface with the browser’s JavaScript engine. Unity WebGL provides different methods to do this.
The recommended way of using browser JavaScript in your project is to add your JavaScript sources to your project, and then call those functions directly from your script code. To do so, place files with JavaScript code using the .jslib
extension in the Assets folder > Plugins subfolder. The plugin file needs to have a syntax like this:
mergeInto(LibraryManager.library, {
Hello: function () {
window.alert("Hello, world!");
},
HelloString: function (str) {
window.alert(UTF8ToString(str));
},
PrintFloatArray: function (array, size) {
for(var i = 0; i < size; i++)
console.log(HEAPF32[(array >> 2) + i]);
},
AddNumbers: function (x, y) {
return x + y;
},
StringReturnValueFunction: function () {
var returnStr = "bla";
var bufferSize = lengthBytesUTF8(returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
},
BindWebGLTexture: function (texture) {
GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]);
},
});
Then, you can call these functions from your C# scripts as follows:
using UnityEngine;
using System.Runtime.InteropServices;
public class NewBehaviourScript : MonoBehaviour {
[DllImport("__Internal")]
private static extern void Hello();
[DllImport("__Internal")]
private static extern void HelloString(string str);
[DllImport("__Internal")]
private static extern void PrintFloatArray(float[] array, int size);
[DllImport("__Internal")]
private static extern int AddNumbers(int x, int y);
[DllImport("__Internal")]
private static extern string StringReturnValueFunction();
[DllImport("__Internal")]
private static extern void BindWebGLTexture(int texture);
void Start() {
Hello();
HelloString("This is a string.");
float[] myArray = new float[10];
PrintFloatArray(myArray, myArray.Length);
int result = AddNumbers(5, 7);
Debug.Log(result);
Debug.Log(StringReturnValueFunction());
var texture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
BindWebGLTexture(texture.GetNativeTexturePtr());
}
}
More Details:
UTF8ToString
helper function to convert to a JavaScript string._malloc
to allocate some memory and the stringToUTF8
helper function to write a JavaScript string to it. If the string is a return value, then the IL2CPP runtime automatically frees up the memory for you.emscripten
provides different ArrayBufferViews
into its heap for different sizes of integer, unsigned integer or floating point representations of memory: HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64.GL.textures
array which maps native texture IDs from Unity to WebGL texture objects. You can call WebGL functions on emscripten’s WebGL context, GLctx
.JavaScript와 인터랙션하는 방법에 대한 자세한 내용은 emscripten 문서를 참조하십시오.
In addition, there are several plugins in the Unity installation folder that you can use as reference: PlaybackEngines/WebGLSupport/BuildTools/lib
and PlaybackEngines/WebGLSupport/BuildTools/Emscripten/src/library*
.
The recommended approach is to execute all the build code in its own scope. This allows you to embed your content on an arbitrary page without causing conflicts with the embedding page code, and lets you embed more than one build on the same page.
모든 JavaScript 코드가 .jslib 플러그인 형태로 프로젝트 안에 있는 경우 이 JavaScript 코드는 컴파일된 빌드와 같은 스코프 안에서 실행되고, 코드는 이전 Unity 버전과 동일한 방법으로 작동합니다. 예를 들어 Module, SendMessage, HEAP8, ccall 등과 같은 오브젝트와 함수는 JavaScript 플러그인 코드에서 직접 볼 수 있습니다.
However, if you are planning to call the internal JavaScript functions from the global scope of the embedding page, you must use the unityInstance
variable in your WebGL Template index.html
. Do this after the Unity engine instantiation succeeds, for example:
var myGameInstance = null;
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {...}).then((unityInstance) => {
myGameInstance = unityInstance;
…
Then, you can send a message to the build using myGameInstance.SendMessage()
, or access the build Module object using myGameInstance.Module
.
The recommended way of sending data or notification to the Unity script from the browser’s JavaScript is to call methods on GameObjects in your content. If you are making the call from a JavaScript plugin, embedded in your project, you can use the following code:
MyGameInstance.SendMessage(objectName, methodName, value);
여기에서 objectName 은 씬에 있는 오브젝트의 이름이고, methodName 은 해당 오브젝트에 현재 연결된 스크립트에 있는 메서드의 이름이고, value 는 문자열 또는 숫자이거나 비어 있을 수 있습니다. 예:
MyGameInstance.SendMessage('MyGameObject', 'MyFunction');
MyGameInstance.SendMessage('MyGameObject', 'MyFunction', 5);
MyGameInstance.SendMessage('MyGameObject', 'MyFunction', 'MyString');
If you would like to make a call from the global scope of the embedding page, see the Code Visibility section.
Unity compiles your sources into JavaScript from C/C++ code using emscripten, so you can also write plugins in C/C++ code, and call these functions from C#. Therefore, instead of the .jslib
file in the example above, you could have a C/C++ file in your project, which is automatically get compiled with your scripts, and you can call functions from it, just like in the JavaScript example above.
If you are using C++ (.cpp) to implement the plugin, then you must ensure the functions are declared with C linkage to avoid name mangling issues:
# include <stdio.h>
extern "C" void Hello ()
{
printf("Hello, world!\n");
}
extern "C" int AddNumbers (int x, int y)
{
return x + y;
}
Note: Unity is using the Emscripten version 2.0.19 toolchain.
2021.2 이상에서 Pointer__stringify()를 UTF8ToString으로 교체함
2020.1에서 unity.Instance가 createUnityInstance로 대체됨
코드 예제에서 오류 수정
2019.1에서 WebGL 인스턴스의 이름이 gameInstance에서 unityInstance로 변경됨