Skip to main content

Creating Android Plugins For Unity



Creating Android Plugins For Unity

When creating a game / app with Unity which targets a specific platform like Android or iOS it would really handy if you could access some  platform specific features such as native pop-up windows ( modal dialogs ), battery status, vibration access, location access, file system access etc.. 

*Note : The following tutorial assumes that you know a bit about Android development and java in general. Even if you don't know android development I hope this tutorial shows you how easy and rewarding it is to make your own Android plugins.
Before we start you should make a folder called 'Plugins' inside the 'Assets' directory and inside that create a 'Android' folder.
This is where all our .aar / .jar files go which is basically a .dll file for windows folks.
We will be making a plugin that displays a Toast dialog which consists of a string we pass
from Unity and also a method that performs some math operation and returns the output to Unity.

Let's Start

  1. Open Android Studio and create a new project.
  2. Set up the minimum & target Sdk versions.
  3. We do not need an activity, So choose no activity.
  4. Now we have to create a new module.

    Then select 'Android Library'.

    Then set the library name.
  5. Now we have to create a new java class.

    And we create a singleton class.
  6. In the 'Helper' class we write the function that we will be calling from Unity side.
    package com.bitshiftprogrammer.androidplugin.testlibrary;
    
    import android.app.Activity;
    import android.content.Context;
    import android.util.Log;
    import android.widget.Toast;
    
    public class Helper {
        private static final Helper ourInstance = new Helper();
    
        public static Helper getInstance() {
            return ourInstance;
        }
    
        private Helper()
        {
            Log.v("Unity", "Helper Object Created");
        }
    
        public int ShowToastMessage(Context ac , String message)
        {
            Toast.makeText(ac, message, Toast.LENGTH_LONG).show();
            return 1;
        }
    
        public int PerformMath(int x)
        {
            return x+10;
        }
    }
    
    This class consists of 2 functions both of which are public. Also the constructor of our Helper class prints out 'Helper Object Created' when it is called.
    These 'Log' statements can be seen in the LogCat of our Android studio when we have either a phone or an Android emulator running.
    *Note : int ShowToastMessage(Context , String) :-
    This method returns '1'. This is just there so that we can call this method from Unity ( AndroidJavaClass in Unity doesn't seem to support methods that return 'void' as far as I'm aware. 😐 ).
    We need to pass in a 'Context' as well, This can be given from Unity side by taking the current running activity's context ( We will see this being done soon ).
  7. Now we need to build this and get the .aar that was generated and put that in our Plugins folder in Unity.

    The .aar can be found at Project Location > Your Library > Build > Outputs > aar.
  8. Now the Unity side of things.
    using UnityEngine;
    
    public class AndroidPluginManager : MonoBehaviour
    {
        const string pluginName = "com.bitshiftprogrammer.androidplugin.testlibrary.Helper";
    
        static AndroidJavaClass pluginClass;
        static AndroidJavaObject pluginObject;
        static AndroidJavaObject context;
    
        void Start()
        {
            pluginClass = new AndroidJavaClass(pluginName);
            pluginObject = pluginClass.CallStatic<AndroidJavaObject>("getInstance");
    
            AndroidJavaObject currentActivity;
            AndroidJavaClass UnityPlayer;
    
            UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            currentActivity = UnityPlayer.GetStatic("currentActivity");
            context = currentActivity.Call("getApplicationContext");
        }
        public void ShowTimeToast()
        {
            pluginObject.Call<int>("ShowToastMessage", context, ("Time is = " + Time.time));
        }
        public void PeformAddByTen()
        {
            Debug.Log("From Unity : Called perform math : " + pluginObject.Call<int>("PerformMath", 14));
        }
    }
    
    Here we use the 'AndroidJavaClass' & 'AndroidJavaObject' which are predefined classes to access native Android functionalities.
    First we have to find 'Helper' class that we made, So for that we have to pass in the complete path of the class by including it's package name.
    In this example the package name is : 'com.bitshiftprogrammer.androidplugin.testlibrary' and the class name is 'Helper'.
  9. The 'AndroidJavaClass' object would be created like this:
    pluginClass = new AndroidJavaClass("com.bitshiftprogrammer.androidplugin.testlibrary.Helper").
    After we have found the class, we then need to get an instance of that class ( object ).
    Since this class is a singleton, An object of that class has already been created and we can get it by calling the 'getInstance' static method of the 'Helper' class.
    We can call static methods in a class by using the 'CallStatic<return type>("method name")' of an 'AndroidJavaClass' object.
    This is done like this : pluginClass.CallStatic<AndroidJavaObject>("getInstance")
  10. Now that we have access to the object we can now call the methods. In order to call these methods we use the 'Call<return type>(param object[])' method available for a 'AndroidJavaObject' object. In this method any number of parameters of any type can be passed in.
    So for the 'PerformMath' method we are giving an integer '14' and the method returns '14 + 10' as the output which we receive in Unity.
    And for the 'ShowToastMessage' method we pass in our current context ( not going into what a context is. 😁 ) and the message we want the toast to display.
Toast Example
The final step is just calling these functions in Unity. I have attached them to simple Unity buttons.
Logcat printed statements
You just have to build and run it on your Android phone. To see the Logs that are generated just connect your phone via USB while Android Studio is opened and check the Logcat.

That's it! Hope you learnt something. Support Bitshift Programmer by leaving a like on Bitshift Programmer Facebook Page and be updated as soon as there is a new blog post.
If you have any questions that you might have about shaders or unity development in general don't be shy and leave a message on my facebook page or down in the comments.
For more Unity development tutorials, go : HERE
For Shader development tutorials, go : HERE

POPULAR POSTS

Toon Liquid Shader - Unity Shader

Toon Liquid Shader This is how the shader will end up looking :
This shader is pretty neat and somewhat easy to implement as well as to understand. Since we will be adding some basic physics to the toon water as it is moved about we will have to support that in the vertex shader as well.
So let's start by looking at the properties :
Properties { _Colour ("Colour", Color) = (1,1,1,1) _FillAmount ("Fill Amount", Range(-10,10)) = 0.0 [HideInInspector] _WobbleX ("WobbleX", Range(-1,1)) = 0.0 [HideInInspector] _WobbleZ ("WobbleZ", Range(-1,1)) = 0.0 _TopColor ("Top Color", Color) = (1,1,1,1) _FoamColor ("Foam Line Color", Color) = (1,1,1,1) _Rim ("Foam Line Width", Range(0,0.1)) = 0.0 _RimColor ("Rim Color", Color) = (1,1,1,1) _RimPower ("Rim Power", Range(0,10)) = 0.0 } Just the usual stuff that we are used to. The only thing that may stand out is the [HideInInspector] tag, This works j…

Introduction To Bitwise Operations

Introduction To Bitwise Operations Bitwise operators are used to change individual bits in an operand. The main use of bitwise operations are to perform calculations at a more optimized level as these operations are directly supported by the processor. & (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
eg: 1010 & 0010 = 0010| (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
eg: 1001 | 0010 = 1011 ^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
eg: 0110 ^ 1000 = 1110<< (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
eg: 0101 << 1 = 1010>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second…