从 C# 中使用插件
构建插件之后,束应被放在 Unity 工程的
文件夹中(或对应的特定结构子文件夹内)。若在 C# 脚本中定义如下函数,Unity 将按名称查找插件:-[DllImport ("PluginName")] private static extern float FooPluginFunction ();
请注意:PluginName 不应包含库后缀名或文件扩展名。例如,在 Windows 中,插件文件的实际名称可以是 PluginName.dll,在 Linux 中可以是 libPluginName.so。
需注意的是,每次在插件 (Plugin) 中更改代码之后,都必须在工程中重新编译脚本,否则,插件将不会包含最新编译的代码。
部署
对于跨平台插件,必须在插件 (Plugins) 文件夹内包含 .bundle (Mac)、.dll (Windows) 和 .so (Linux) 文件。 之后,无需进行其他工作。Unity 将自动为目标平台选择正确的插件,并将其打包至播放器。
示例
最简单的插件
此插件工程仅实现了一些最基本的操作(打印数字、打印字符串、添加两个浮点、添加两个整数)。如果这是您的第一个 Unity 插件,此示例将很有帮助。
此工程可在此处查看,且包含 Windows、Mac、和 Linux 工程文件。
例子如下:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
public class PluginImport : MonoBehaviour {
//Lets make our calls from the Plugin
[DllImport ("ASimplePlugin")]
private static extern int PrintANumber();
[DllImport ("ASimplePlugin")]
private static extern IntPtr PrintHello();
[DllImport ("ASimplePlugin")]
private static extern int AddTwoIntegers(int i1,int i2);
[DllImport ("ASimplePlugin")]
private static extern float AddTwoFloats(float f1,float f2);
void Start () {
Debug.LogError(PrintANumber());
Debug.Log(Marshal.PtrToStringAuto (PrintHello()));
Debug.Log(AddTwoIntegers(2,2));
Debug.Log(AddTwoFloats(2.5F,4F));
}
}
输出:
每次调用插件中的方法都要写一次引用插件名;并且插件必须放在Plugins文件夹下面