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

Assets Worth Checking Out

POPULAR POSTS

Introduction To Replacement Shaders & Shader Keywords

What is a replacement shader? A replacement shader is a shader that gets applied to every object being rendered.
Since the camera determines what objects end up being shown on screen, The functionality for setting up replacement shaders are in the camera class as well.

A good use case of a replacement shader would be in making effects like SSAO.
Here we need access to the normals and the depth information so a replacement shader that displays only the normals can be rendered ( stored in a render texture ) and then another shader that displays the depth information ( stored in a render texture ) and then the final image is rendered with the SSAO effect by taking the two render textures as input and doing a bunch of calculations.

Another use case would be to visualize the environment differently for various reasons like how they did in City Skylines.

The function that performs shader replacement is:
Camera.SetReplacementShader( Shader shader, string replacementTag ) Takes in a shader as …

Curved Surface Shader [ Unity Implementation ]

Curved Surface Shader This is the shader that we will be having at the end of this tutorial.
 The curved surface shader is capable of achieving really varied visual effects from showing space-time curve due to gravity to a generic curved world shader that is seen in endless runners like Subway Surfers.
The concepts that you learn here can open you up to a new way of looking at shaders and if you didn't think they were the coolest thing ever already, hopefully let this be the turning point.😝.

Both the examples show above use the same exact material is just that different values have been passed to the shader.
Start by creating a new unlit shader in Unity and we will work our way from there.
First we define what the properties are:
_MainTex("Texture", 2D) = "white" {} _BendAmount("Bend Amount", Vector) = (1,1,1,1) _BendOrigin("Bend Origin", Vector) = (0,0,0,0) _BendFallOff("Bend Falloff", float) = 1.0 _BendFallOffStr("Falloff s…

Noise Generation Algorithms : White Noise With Shader Example

White Noise Many of you may know what white noise is and how it can be used in code.
But there are a spectrum of  'Coloured Noises' as well these include ones like brown noise, pink, blue and violet noise all these have slightly different properties and can be very useful in creating different effects. More details on coloured noises can be found HERE.
A lot of movies as well as video games like City Skylines use white noise to add a feeling of realism and texture to the on screen content, it's also referred to as a grain filter or overlay. It is a really subtle effect and should not be over used.
Creating white noise boils down to the random function used.
While writing C++ code or C# code we have access to good pseudo-random functions from their standard libraries... but while writing code in shaders we usually have to create our own pseudo-random number generator.
One really good way of making one is by using the frac( in Unity & HLSL ) or fract( in GLSL ) functio…

Alto's Adventure Style Procedural Surface Generation Part 1

Alto's Adventure Style - Procedural Surface Generation This game appears to be a strictly 2D game but if you have played it enough you will notice that some of the art assets used look like it's 3D ( I don't know if they are tho ). If you haven't played the game you are missing out on one the most visually pleasing and calming games out there ( There is literally a mode called Zen mode in the game ).
Anyway, I am going to show you how to make a procedural 2D world ( without the trees, buildings and background ) like in Alto's Adventure.
But you may notice I have a plane which is in in the Z-axis giving a depth to the surface which is not there in Alto's Adventure but if you want to know how to do it then that will be in part 2.
To achieve the same effect of Alto's Adventure ( I'm leaving that up to you ) only minimal changes are needed to the code that I am going to explain.
We are going to be using the plane mesh in unity for creating the 2D surface as th…

Making An Audio Visualizer In Unity With Blend Shapes & Audio API - Part 1

Audio Visualizer with Unity Audio API & Blend Shapes This tutorial is going to be split into two parts, The first part (this one) we are going to be covering Blendshapes, what they are, what it's used for and how to use them in Unity and in Part 2 we will cover integrating that with Unity's audio API to get the desired result.
So now you got a feel as to what we will be making.
Blendshapes are just like transitions that the vertices go through to go from being in one position in space to another with the help of a transition value. All the major 3d modelling software from Blender to Maya has it.
As you can see that the model has 2 shape keys, one called MinValue and another called MaxValue, these names don't carry over into unity but the index of the shape key( blend shape ) matters.
We will be manipulating the MaxValue to make changes to the mesh.
This is how the model looks when it has it's MaxValue set at zero.
You may have guessed now that it is just a basic linear i…