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

Comments

  1. Unity 3D is highly preferred for its extended support to 27 platforms. The app developed and deployed can be easily shared between PC, web and mobile platforms. Besides, the agile methodology enables speedy prototyping and constant releases, which in turn speed up the game development in UK.

    ReplyDelete
  2. Thanks for the useful information, give more updates like First time I visit your site really nice, here after a daily visit.
    ecommerce website development company in chennai

    ReplyDelete

Post a Comment

Assets Worth Checking Out

POPULAR POSTS

Pixelation Shader - Unity Shader

Pixelation Shader This is the correct way (one of many) of showing pixelation as a post-processing effect. This effect will work in any aspect ratio without any pixel size scaling issues as well as it is very minimal in terms of coding it up.

In order to get this to work 2 components have to be set up:
1) The pixelation image effect
2) The script - which will be attached to the camera

So let's get started by creating a new image effect shader.
We will take a look at our Shaderlab properties :
_MainTex("Texture", 2D) = "white" {} That's it, Everything else will be private and not shown in the editor.
Now we will see what are defined along with the _MainTex but are private.
sampler2D _MainTex; int _PixelDensity; float2 _AspectRatioMultiplier; We will pass _PixelDensity & _AspectRatioMultiplier values from the script.
As this is an image effect there is no need to play around with the vertex shader.
Let's take a look at our fragment shader:
fixed4 frag (…

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…

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…

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…

Advanced Billboard Shader + World-Space UI Support

Advanced Billboard Shader + World-Space UI SupportAs you know billboarding is basically a plane with a texture on it that always facing the camera.These are some examples of what we are going for. This tutorial is going to be pretty straight-forward and easy to follow along you will learn how to make a billboard shader that not only keeps looking at the camera but also keeps its relative scaling intact.We will also provide an option to keep it rendered on top of all the other objects in the scene. This will be most useful for world-space UI that needs to be rendered on top of other geometry.We will be making 2 shaders here,Modified Default Unlit shader :- This one is a general shader ( easy to modify furthur ).Modified Default UI shader :- This one supports whatever a UI shader supports along with our billboarding capabilities. So let's get started with making the first one. As usual create a new Unlit shader and dive into the properties we need.Properties { _MainTex ("Texture…