文档

Unity 引擎

Unity 引擎

代码示例:在 Unity 中调用 Javascript 和 C/C++/C# 函数

代码示例,显示 Unity、JavaScript 和基于 C 的代码之间的交互。
阅读时间3 分钟最后更新于 5 天前

您可以使用代码来执行插件与 Unity 代码之间的交互。以下示例展示了如何在 Unity 项目中从 Javascript 和 C/C++/C# 代码调用各种类型的函数。

在 Unity C# 示例中调用 Javascript 代码

以下代码是 Unity C# Script可以从中调用函数的 Javascript 代代码示例。
mergeInto(LibraryManager.library, { Hello: 函数 () { window.alert("Hello, world!"); }, HelloString:函数 (str) { window.alert(UTF8ToString(str)); }, PrintFloatArray:函数 (Array, 大小) { for(var i = 0; i < size; i++) console.log(HEAPF32[(array >> 2) + i]); }, AddNumbers:函数 (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:函数(纹理){ GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]); },});
以下代码是 Unity C# 代码的示例,用于Calls Javascript 示例中定义的函数。
using UnityEngine;using System.Runtime.InteropServices;public class NewBehaviourScript :MonoBehaviour { [DllImport("__Internal")] private static extern void Hello(); [DllImport("__Internal")] private static extern void HelloString(字符串 str); [DllImport("__Internal")] private Static extern void 浮点 Array 整型 大小; [DllImport("__Internal")] private Static extern 整型 AddNumbers(整型 x,整型 y); [DllImport("__Internal")] private Static extern 字符串 StringReturnValueFunction(); [DllImport("__Internal")] private Static extern void BindWebGLTexture(整型纹理); void Start() { Hello(); HelloString("This is a string."); float[] myArray = 新建 float[10]; PrintFloatArray(myArray, myArray.Length); 整型 result = AddNumbers(5, 7); Debug.Log(result); Debug.Log(StringReturnValueFunction()); var texture = new Texture2D(1, 1, TextureFormat.ARGB32, false); BindWebGLTexture(texture.GetNativeTexturePtr()); }}

在 Unity C# 脚本示例中调用 C/C++/C# 代码

以下代码是一个 C++ 插件示例,其中包含可在 Unity Project 中调用的 Simple 函数。
#include <stdio.h>extern "C" void Hello (){ printf("Hello, world!\n");}extern "C" 整型 AddNumbers(整型 x、整型 y){ return x + y;}
然后,在 Unity Project使用以下 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 整型 AddNumbers(整型 x,整型 y); void Start() { Hello(); 整型 result = AddNumbers(5, 7); Debug.Log(result); }}

其他资源