Version: 2017.2
WebGL 타게팅 시 메모리에 대해 고려할 사항(Memory Considerations when targeting WebGL)
WebGL 템플릿 사용

WebGL: 브라우저 스크립트와 상호작용

웹용 콘텐츠를 빌드할 때 웹페이지의 다른 요소와 통신해야 할 수 있습니다. 또는 Unity 에디터가 현재 기본적으로 노출하지 않는 웹 API를 사용하여 기능을 구현하고 싶을 수 있습니다. 두 가지 경우에 모두 브라우저의 JavaScript 엔진과 직접 상호작용해야 합니다. Unity WebGL은 이렇게 할 수 있는 몇 가지 방법을 제공합니다.

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

브라우저 JavaScript를 프로젝트에 사용하려면 JavaScript 소스를 프로젝트에 추가한 다음 해당 함수를 스크립트 코드에서 직접 호출하는 방법이 권장됩니다. 이렇게 하려면 JavaScript 코드를 통해 .jslib 확장자(일반 .js는 UnityScript 컴파일러에서 픽업될 것이므로)를 사용하여 파일을 Assets 폴더의 “Plugins” 하위 폴더에 저장해야 합니다. 플러그인 파일에는 다음과 같은 구문이 있어야 합니다.

mergeInto(LibraryManager.library, {

  Hello: function () {
    window.alert("Hello, world!");
  },

  HelloString: function (str) {
    window.alert(Pointer_stringify(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]);
  },

});

그러면 다음과 같이 C# 스크립트에서 이러한 함수를 호출할 수 있습니다.

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(0, 0, TextureFormat.ARGB32, false);
        BindWebGLTexture(texture.GetNativeTextureID());
    }
}

Simple numeric types can be passed to JavaScript in function parameters without requiring any conversion. Other data types will be passed as a pointer in the emscripten heap (which is really just a big array in JavaScript). For strings, you can use the Pointer_stringify helper function to convert to a JavaScript string. To return a string value you need to call _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 will take care of freeing the memory for you. For arrays of primitive types, emscripten provides different ArrayBufferViews into it’s heap for different sizes of integer, unsigned integer or floating point representations of memory: 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. WebGL functions can be called on emscripten’s WebGL context, GLctx.

Unity 에디터에서 JavaScript를 호출하는 기존 방법

참고: Unity 5.6부터 .jslib 플러그인을 통해 Unity 에디터에서 JavaScript 코드를 호출하는 방법이 권장됩니다. 아래에서 설명하는 방법은 호환성을 유지하기 위한 이유로만 지원되고, 향후 Unity 버전에서는 지원이 중단될 수 있습니다.

Application.ExternalCall() 함수와 Application.ExternalEval() 함수를 사용하여 임베딩 웹페이지에서 JavaScript 코드를 호출할 수 있습니다. 빌드의 로컬 스코프 내에서 식이 계산됩니다. JavaScript 코드를 전역 스코프에서 실행하려면 아래의 코드 가시성 섹션을 참조하십시오.

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

때로는 데이터나 알림을 브라우저의 JavaScript에서 Unity 스크립트로 보내야 하는 경우가 있습니다. 이 작업에는 콘텐츠의 게임 오브젝트에서 메서드를 호출하는 방법이 권장됩니다. 프로젝트에 내장된 JavaScript 플러그인에서 호출하는 경우 다음 코드를 사용할 수 있습니다.

SendMessage(objectName, methodName, value);

여기에서 objectName 은 씬에 있는 오브젝트의 이름이고, methodName 은 해당 오브젝트에 현재 연결된 스크립트에 있는 메서드의 이름이고, value 는 문자열 또는 숫자이거나 비어 있을 수 있습니다. 예:

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

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

임베딩 페이지의 전역 스코프에서 호출하려면 아래의 코드 가시성 섹션을 참조하십시오.

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

Unity 에디터는 emscripten을 사용하여 C++ 코드에서 JavaScript로 소스를 컴파일하기 때문에 C 또는 C++ 코드로 플러그인을 작성하고 C#에서 함수를 호출할 수 있습니다. 따라서 위 예의 jslib 파일 대신 아래와 같은 C 파일이 프로젝트에 포함될 수 있습니다. 이 파일은 자동으로 스크립트로 컴파일되고 위의 JavaScript 예처럼 이 파일에서 함수를 호출할 수 있습니다.

C++(.cpp)로 플러그인을 구현하는 경우 이름 맹글링 문제를 방지하기 위해 함수가 C 링크로 선언되도록 해야 합니다.

# include <stdio.h>
void Hello ()
{
    printf("Hello, world!\n");
}
int AddNumbers (int x, int y)
{
    return x + y;
}

코드 가시성

Unity 5.6부터 모든 빌드 코드가 자체 스코프에서 실행됩니다. 이 방법을 통해 임베딩 페이지 코드와 충돌을 일으키지 않고 임의 페이지에 게임을 임베드할 수 있고 같은 페이지에 빌드를 두 개 이상 임베드할 수도 있습니다.

모든 JavaScript 코드가 .jslib 플러그인 형태로 프로젝트 안에 있는 경우 이 JavaScript 코드는 컴파일된 빌드와 같은 스코프 안에서 실행되고, 코드는 이전 Unity 버전과 거의 동일한 방법으로 작동합니다. 예를 들어 Module, SendMessage, HEAP8, ccall 등과 같은 오브젝트와 함수는 JavaScript 플러그인 코드에서 직접 볼 수 있습니다.

하지만 임베딩 페이지의 전역 스코프에서 내부 JavaScript 함수를 호출할 계획이라면 항상 페이지에 여러 빌드가 임베드되었다고 가정해야 하므로 어느 빌드를 레퍼런스하고 있는지 명시적으로 지정해야 합니다. 예를 들어 게임이

var gameInstance = UnityLoader.instantiate("gameContainer", "Build/build.json", {onProgress: UnityProgress});

으로 인스턴스화된 경우 gameInstance.SendMessage()를 사용하여 메시지를 빌드로 전송하거나 이 gameInstance.Module 같은 빌드 모듈 오브젝트에 액세스할 수 있습니다.


  • 2017–11–14 편집 리뷰 없이 페이지 수정됨

  • 코드 예제에서 오류 수정

  • Unity 5.6에서 업데이트됨

WebGL 타게팅 시 메모리에 대해 고려할 사항(Memory Considerations when targeting WebGL)
WebGL 템플릿 사용