Version: 2023.2
언어: 한국어
Web Player settings
Web native plug-ins for Emscripten

브라우저 스크립팅과 상호작용

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 Web provides different methods to do this.

Unity 스트립트에서 JavaScript 함수 호출

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 sub-folder. The plug-in 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:

  • You can pass simple numeric types to JavaScript in function parameters without doing any conversion. You can pass other data types as a pointer in the Emscripten heap which is just a big array in JavaScript.
  • 문자열의 UTF8ToString 헬퍼 함수를 사용하여 JavaScript 문자열로 전환할 수 있습니다.
  • 문자열 값을 반환하려면 _malloc를 호출하여 일부 메모리를 할당하고 stringToUTF8 헬퍼 함수를 호출하여 JavaScript 문자열을 작성해야 합니다.문자열이 반환 값인 경우 IL2CPP 런타임이 가용 메모리를 늘리는 작업을 자동으로 처리합니다.
  • 프리미티브 타입 배열의 경우 emscripten은 다음과 같은 여러 정수 크기, 서명되지 않은 정수 또는 부동 소수점 메모리 표현에 대해 각기 다른 ArrayBufferViews를 힙에 제공합니다.HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64
  • To access a texture in WebGL, Emscripten provides the 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.

For more information on how to interact with JavaScript, refer to the Emscripten documentation.

There are several plug-ins 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 lets you 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.

If you have all your JavaScript code in the form of .jslib 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. For example, the following objects and functions should be directly visible from the JavaScript plugin code: Module, SendMessage, HEAP8, ccall etc..

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 Web 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.

JavaScript에서 Unity 스크립트 함수 호출

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 plug-in, embedded in your project, you can use the following code:

MyGameInstance.SendMessage(objectName, methodName, value);

Where objectName is the name of an object in your scene; methodName is the name of a method in the script, currently attached to that object; value can be a string, a number, or can be empty. For example:

MyGameInstance.SendMessage('MyGameObject', 'MyFunction');
MyGameInstance.SendMessage('MyGameObject', 'MyFunction', 5);

MyGameInstance.SendMessage('MyGameObject', 'MyFunction', 'MyString');

To make a call from the global scope of the embedding page, refer to the Code Visibility section.

Unity 스트립트에서 C 함수 호출

Unity compiles your sources into JavaScript from C/C++ code using Emscripten, so you can also write plug-ins in C/C++ code, and call these functions from C#. Therefore, instead of the .jslib file in the above example, use a C/C++ file in your project, which can be automatically compiled with your scripts, and you can call functions from it.

If you are using C++ (.cpp) to implement the plug-in, then you must declare the functions 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;
}

참고:Unity는 Emscripten 버전 2.0.19 툴체인을 사용하고 있습니다.

Web Player settings
Web native plug-ins for Emscripten