扩展 UnityPlayerActivity Java 代码
Using Java or Kotlin source files as plug-ins

适用于 Android 的原生 (C++) 插件

Unity supports native plug-ins for Android written in C/C++ and packaged in a shared library (.so) or a static library (.a). When using the IL2CPP scripting backend, you can use C/C++ source files as plug-ins and Unity compiles them along with IL2CPP generated files. This includes all C/C++ source files with extensions .c, .cc, .cpp and .h.

To build a C++ plug-in for Android, use the Android NDK and get yourself familiar with the steps required to build a shared library. The same applies to static libraries.

If you are using C++ to implement the plug-in, you must ensure the methods are declared with C linkage to avoid name mangling issues. By default, only the C source files that have a .c file extension in the plug-ins have C linkage (not C++).

extern "C" {
  float Foopluginmethod ();
}

构建库后,将输出的 .so 文件复制到 Unity 项目的 Assets/Plugins/Android 目录中。在 Inspector 中,将 .so 文件标记为与 Android 兼容,并在下拉框中设置所需的 CPU 架构:

Inspector 窗口中显示的原生 (C++) 插件导入设置
Inspector 窗口中显示的原生 (C++) 插件导入设置

要从 C# 脚本调用原生插件中的方法,请使用以下代码:

[DllImport ("pluginName")]
private static extern float Foopluginmethod();

请注意,pluginName 不应包含文件名的前缀(“lib”)和扩展名(“.so”)。建议使用额外的 C# 代码层包装所有的原生插件方法调用。此代码将检查 Application.platform 并仅当应用程序在实际设备上运行时才调用本机方法;在 Editor 中运行时,将从 C# 代码返回虚拟值。请使用平台定义来控制依赖于平台的代码编译。

When you use C/C++ source files as plug-ins, you call them from C# in the same way except that you use __Internal for plug-in name, for example:

[DllImport ("__Internal")]
private static extern float Foopluginmethod();

Native (C++) plug-in Sample

The AndroidNativePlugin.unitypackage zip file contains a simple example of a native code plug-in distributed as Unity package.

The sample shows how to invoke C++ code from a Unity application. The package includes a scene which displays the sum of two values as calculated by the native plug-in. To compile the plug-in must install the Android NDK.

To install the sample:

  1. Download the the zip file.
  2. Extract the AndroidNativePlugin.unitypackage file.
  3. Open the Unity Editor.
  4. Create a new Project.
  5. In the new project click Assets > Import Package &gt Custom Package.
  6. In the Import Package file dialog, navigate to the location in which you extracted the file and select it.

  • 2018–12–21 Page amended with editorial review
  • 2018–03–10 Page published with limited editorial review
  • 5.5 版中的更新功能
  • Support for using C++ source files and static libraries as plug-ins on Android added in 2018.2 NewIn20182
扩展 UnityPlayerActivity Java 代码
Using Java or Kotlin source files as plug-ins