Managed plug-ins
Building plug-ins for desktop platforms

Native plug-ins

Unity has extensive support for native plug-ins, which are libraries of native code written in C, C++, Objective-C, etc. Plug-ins allow your game code (written in Javascript or C#) to call functions from these libraries. This feature allows Unity to integrate with middleware libraries or existing C/C++ game code.

In order to use a native plug-in you firstly need to write functions in a C-based language to access whatever features you need and compile them into a library. In Unity, you will also need to create a C# script which calls functions in the native library.

The native plug-in should provide a simple C interface which the C# script then exposes to other user scripts. It is also possible for Unity to call functions exported by the native plug-in when certain low-level rendering events happen (for example, when a graphics device is created), see the Native plug-in interface page for details.

示例

具有单个函数的非常简单的本机库可能具有如下所示的源代码:

    float FooPluginFunction () { return 5.0F; }

要从 Unity 中访问此代码,可使用如下代码:

    using UnityEngine;
        using System.Runtime.InteropServices;

        class SomeScript : MonoBehaviour {

           #if UNITY_IPHONE
   
           // 在 iOS 上,插件以静态方式链接到
           //可执行文件中,因此我们必须使用 __Internal 作为
           // 库名。
           [DllImport ("__Internal")]

           #else

           // 其他平台会动态加载插件,因此
           // 传递插件动态库的名称。
           [DllImport ("PluginName")]
    
           #endif

           private static extern float FooPluginFunction ();

           void Awake () {
              // 在插件中调用 FooPluginFunction
              // 并将 5 输出到控制台
              print (FooPluginFunction ());
           }
        }

Note that when using Javascript you will need to use the following syntax, where DLLName is the name of the plug-in you have written, or “__Internal” if you are writing statically linked native code:

    @DllImport (DLLName)
        static private function FooPluginFunction () : float {};

Creating a native plug-in

In general, plug-ins are built with native code compilers on the target platform. Since plug-in functions use a C-based call interface, you must avoid name mangling issues when using C++ or Objective-C.

其他信息

Managed plug-ins
Building plug-ins for desktop platforms