Android Plugins 101 - An Introduction
This topic is the first part of a series on how to create Android Plugins for Unity. Start here if you have little to no experience creating plugins, and/or the Android OS.
Through this series, I extensively use external links that I encourage you to read. While paraphrased versions of the relevant content will be included here, there may be times when the additional reading will help.
Beginning with Android plugins
Currently, Unity provides two ways to call native Android code.
- Write native Android code in Java, and call these Java functions using C#
- Write C# code to directly call functions that are part of the Android OS
To interact with native code, Unity provides some classes and functions.
- AndroidJavaObject - This is the base class that Unity provides to interact with native code. Almost any object returned from native code can be stored as and AndroidJavaObject
- AndroidJavaClass - Inherits from AndroidJavaObject. This is used to reference classes in your native code
- Get / Set values of an instance of a native object, and the static GetStatic / SetStatic versions
- Call / CallStatic to call native non-static & static functions
Outline to creating a plugin and terminology
- Write native Java code in Android Studio
- Export the code in a JAR / AAR file (Steps here for JAR files and AAR files)
- Copy the JAR / AAR file into your Unity project at Assets/Plugins/Android
- Write code in Unity (C# has always been the way to go here) to call functions in the plugin
Note that the first three steps apply ONLY if you wish to have a native plugin!
From here on out, I'll refer to the JAR / AAR file as the native plugin, and the C# script as the C# wrapper
Choosing between the plugin creation methods
It's immediately obvious that the first way of creating plugins is long drawn, so choosing your route seems moot. However, method 1 is the ONLY way to call custom code. So, how does one choose?
Simply put, does your plugin
- Involve custom code - Choose method 1
- Only invoke native Android functions? - Choose method 2
Please do NOT try to "mix" (i.e. a part of the plugin using method 1, and the other using method 2) the two methods! While entirely possible, it's often impractical and painful to manage.
Create a new Java class in Android Studio and replace it's contents with the following
Create a new C# script in Unity and replace it's contents with the following
Create a new C# script in Unity and paste these contents