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

Gift Wrapping Convex Hull Algorithm With Unity Implementation

Convex Hull Algorithm Convex Hull algorithms are one of those algorithms that keep popping up from time to time in seemingly unrelated fields from big data to image processing to collision detection in physics engines, It seems to be all over the place. Why should you care? Cus you can do magic with it and it seems so simple to implement when you first hear about it, but when you start thinking about it, you will realize why it's not such a straightforward thing to do.
Now that I got you interested (hopefully) and now we will see just what a convex hull is.
As you may have noticed a perimeter was made with the same points that was given and these perimeter points enclose the entire set of points.
Now we have to clear up the term 'Convex'.
Convex means no part of the object is caved inwards or that none of the internal angles made by the points exceed 180 degrees.
In this example of a concave shape internal angles go beyond 180 degrees.
What are those red lines for? Well...…

Shader Optimization Part 1

The process of shader optimization can seem like trial and error... in fact, that's how it is most of the time.
Most of the time shader optimizations could be boiled down to educated guesses because each time a shader gets compiled, the GPU driver of that specific hardware is what converts your code into actual machine code, therefore, the machine code generated will be different for each GPU and the driver itself might perform some optimizations on top of your's which won't be available on another GPU, thereby making it difficult to have a standard way of writing optimal shader code.

So the best way to know for sure is to actually test it on the hardware you are targeting.
With that said, Here are some universal best ways of getting your shader to perform better.😅 Do Calculations On Vertex Shader The most commonly used case for this is lighting, an example would be Gouraud lighting, where lighting calculations are done per vertex but at the loss of quality.

Some calculatio…

Fortnite Procedural Construction Animation Shader

Fortnite Construction Shader This shader is loosely based on the one that was presented by the Fortnite developers in their GDC talk: Inner Working Of Fortnite's Shader-Based Procedural Animations.

 Here is what we will end up with:
This technique requires you to author the 3D model in a certain way, More or less how those Fortnite developers did.
So we need the authored 3D model and the shader that uses data we get from the model to achieve the desired effect.

There are some nuances here and there so make sure you don't miss out on the details.😗
The first step will be preparing the 3D model and putting in the required data. I used Blender 2.79 but any 3D modeling software would do.
3D Model PreparationModel It
Apply Vertex Colors: For the direction of flight
Each color is a component of a vector (x, y, z). This will be considered as local space.
Values range from -1.0 to +1.0 for each component.
Negative values are achieved by using values of less than 0.5 and positive values wi…

Visual Upgrade - Unity Asset Store [ September, 2018 ]

Visual Overhaul - Assets That Turn Mediocre Into Drool Worthy *Note: These assets are not arranged in any way, no comparison is done. They are just really cool assets that will help make your game look at least a bit better. 😁
8. Bat Particles
7.GPU Instancing Animation
6.Colored Pencils
5.Graphics Adapter Pro
4.Sleek Render: Mobile Post Processing
3.1000+ Effects pack
2.COLR - Coloring Redefined
1.AllSky

Check out more such Unity Asset Store Gems : HERE
Don't forget to share these wonderful assets with your colleagues and friends.
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, C# or Unity development in general don't be shy and leave a message on my facebook page or down in the comments.