코드를 사용하여 플러그인과 Unity 코드 간의 상호 작용을 수행할 수 있습니다. 다음 예시는 Unity 프로젝트의 JavaScript 및 C/C++/C# 코드에서 다양한 유형의 함수를 호출하는 방법을 보여 줍니다.
다음 코드는 Unity C# 스크립트에서 함수를 호출할 수 있는 JavaScript 코드 예시입니다.
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]);
},
});
다음 코드는 JavaScript 예시에 정의된 함수를 호출하는 Unity 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(1, 1, TextureFormat.ARGB32, false);
BindWebGLTexture(texture.GetNativeTexturePtr());
}
}
다음은 Unity 프로젝트에서 호출할 수 있는 간단한 함수가 있는 C++ 플러그인 예시입니다.
#include <stdio.h>
extern "C" void Hello ()
{
printf("Hello, world!\n");
}
extern "C" int AddNumbers (int x, int y)
{
return x + y;
}
그런 다음 Unity 프로젝트에서 다음 Unity C# 코드를 사용하여 C++ 함수를 호출합니다.
using UnityEngine;
using System.Runtime.InteropServices;
public class NewBehaviourScript : MonoBehaviour {
[DllImport("__Internal")]
private static extern void Hello();
[DllImport("__Internal")]
private static extern int AddNumbers(int x, int y);
void Start() {
Hello();
int result = AddNumbers(5, 7);
Debug.Log(result);
}
}