Passing Message from a Alert Dialog Box to Unity3D – Part II

Just a quick recap –  we have created an Android module for displaying a native android alert dialog box in an android studio. Which we can call from our Unity3D project and when we will hit yes or no it will pass a message to unity3D on so that we can write our logic.

If you have not followed the last post of this series then Click Here.

In this post, we will see how to create Unity3D project through which we will invoke Alert Dialog Box via a native plugin that we had created in Part I of this post.

  • Open Unity3D and create a new project – AlertDialogBoxForAndroid‘.

And just like we did in Simple Android Plugin for Unity3D – Part 2.

  • Open build settings of the project, and switch to android.
  • Create a new folder – ‘Scene‘ and make an empty scene in that folder by Right Click > New> Scene. Name this scene as scene and add it in build settings.
  • Create a new folder – ‘Scripts’ in asset folder.
  • Create a new folder – ‘Plugins’ in asset folder.
  • Create a new folder – ‘Android’ in Plugin folder created above.
  • Create another new folder – ‘libs’ in android folder created above.
  • Paste the classes.jar and AndroidManifest in the libs folder that we had created in part 1 of the post.

 

  • In hierarchy Right Click > UI> Button, to create a button, and name it – ShowDialogBox
  • In hierarchy Right Click > UI> Text, and name it – OutPut to create a label field that will display what button is pressed on the alert dialog box. Position them in whichever fashion that suits you.

 

 

  • Create an empty GameObject in the hierarchy and name it – ‘Controller’. Create a new tag – ‘controller’ and attach it on the gameobject that we had created in this step.

 

  • Create a new C# file name – Controller.cs, in the scripts folder, attach this script on the gameobject – ‘Controller’ that we created in above step.

paste the below code in this class.

 

  • Create another C# file name – ‘AndroidCallbacks.cs’ in scripts folder. And paste the below code in it
  • Drop the script on the button, and add ShowNativeDialogBox() on the OnClick() of the button.
  • Drop the OutPut(Text) we created above on the reply on the Controller.

 

  • Build and run the project on your android device. Cheers!!

 

Download this project or clone it from GitHub

 

If you are curious and want to know about this project, then leave a comment or email me at contact@nipundavid.com

If you are interested to know more about the work I have done than do the same as above 😀

 

Please follow and like us:

Passing Message from a Alert Dialog Box to Unity3D – Part I

In one of my previous post I shared how to call a simple toast message by creating a native android plugin for Unity3D.

In this post we will turn up the notch and create a android plugin to display a alert dialog box with two buttons ‘yes‘ and ‘no‘, which when pressed will pass message in Unity3D so that we can write the logic accordingly.

And it going to take a while so empty your bladders.

 

So lets begin

  • Create a new android project in android studio, name it – ‘DialogBoxPlugin‘.

 

  • Add a empty activity and leave others settings as it is and click ‘finish‘.

 

 

  • The final project will look something like below – we will write all the logic in package name – com.plugin.android.dialogboxmodule‘.

 

  • Change the project view from Android -> Project.

 

 

Here comes a bit tricky part as we are going to pass a message from native android dialog box to unity activity, we need a reference of unity activity which had triggered this dialog box for this we are going to use UnityPlayer class.

  • Go to path C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono\Release\Classes. It may vary if you have installed Unity3D on some other path. Copy the magical class named – classe.jar.

 

  • In android studio expand dialogboxmodule and in libs folder paste the classes.jar from above.

 

  • Switch back to android view in project settings and create a class ShowNativeDialogBox.java  in com.plugin.android.dialogboxmodule. Paste the code below in the java file we have just created. Now in my case when I started referring UnityPlayer class android studio showed error – no such class definition. I tried cleaning, rebuilding and again cleaning and rebuilding. But it went away after I restarted the android studio, maybe this is some issue with the android studio if anyone knows solution then leave a comment. So this is a heads up, don’t freak out if same happens with you.

Let us dissect the code –

public static void ShowDialogPopup(String title, String message, String yesButtonText, String noButtonText)

This is a method that we will call from Unity3D project from C# to invoke the Alert Dialog Box, arguments name are pretty obvious :D.

AlertDialog.Builder dialogPopupBuilder = new AlertDialog.Builder(new ContextThemeWrapper(UnityPlayer.currentActivity, GetTheme()));
dialogPopupBuilder.setTitle(title);
dialogPopupBuilder.setMessage(message);

The above lines of code create a new AlertDialogBox and set title and message that we want. It also set the theme by calling GetTheme with help of ContextThemeWrapper.

dialogPopupBuilder.setPositiveButton(yesButtonText, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        UnityPlayer.UnitySendMessage("AndroidCallBacks", "HandleCallBacks", "0");
    }
});
dialogPopupBuilder.setNegativeButton(noButtonText, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        UnityPlayer.UnitySendMessage("AndroidCallBacks", "HandleCallBacks", "1");
    }
});

This is the soul of this whole project, – ‘AndroidCallBacks’ is a gameobject in unity3D project that will receive messages from this java class and messages will be 0 for yes and 1 for no. We will see how to create AndroidCallBacks gameobject in Unity3D and how it will handle these messages further in this post.

  • Now as we had done in Simple Android plugin for Unity3D – Part 1. Go to Build> Make Module ‘dialogboxmodule’, after gradle is done building the jar right click on the ‘dialogboxmodule‘ module in the project window and click ‘Show in Explorer‘.
  • Go to  DialogBoxPlugin\dialogboxmodule\build\intermediates\bundles\debug , here will find the classes.jar which we are going to use in Unity3d project to call Alert Dialog Box.

 

Ok, I have changed my mind, I have to break this post into two otherwise it will be just scrolling up and down while following this post.

Continue reading…

Download this project or clone it from GitHub

If you are curious and want to know about this project, then leave a comment or email me at contact@nipundavid.com

If you are interested to know more about the work I have done than do the same as above 😀

 

Please follow and like us:

Understanding Shaders 101

The most spooky area of game programming especially if you come from a non-mathematical and non-computers background and want to create super realistic games. I am neither a shader ninja nor expert, so correct me wherever necessary.😇

 

Not everyone can write shaders!

Not trying to kill motivation here 😀

 

I can’t promise that you will be a shader guru after you done with this series of posts, but at least I can give you a start from where to begin. I will share everything that I have learned about shaders in this series of posts – Understanding Shaders 10x. In the end of each post of this series, I will share important links for further study and practice. For better understanding, go through the links mentioned under – More Info.

This post is about the history of shaders and what motivated programmers to use shaders. Will not get into the code, at least not in this post. Just a warm up!!

In the beginning, there were only ‘Fixed Functions’ and it was good

We will not spend too much time on fixed functions as we lot of ground to cover in this post. Fixed function pipeline refers to the older generation pipeline that was not really controllable — the exact method in which the geometry was transformed, and how fragments (pixels) acquired depth and color values were built-in to the hardware and couldn’t change. But then programmable pipeline came that gave lots of flexibility to the programmer. In the fixed pipeline, a lot of work had to be done on the CPU. With GPU’s, you can move that work to the video card processors (which are specially designed for that stuff, and thus VERY quick with it). For example, animating a character with a skeleton. First, we needed to do all the transformations on the CPU. Now we can do it in a vertex shader. That saves time on the CPU, which you can use for other (non-graphical) stuff. Physics or AI.

 

So what exactly are Shaders?

Wikipedia

In the field of computer graphics, a shader is a computer program that is used to do shading: the production of appropriate levels of light, darkness, and color within an image, or, in the modern era, also to produce special effects or do video post-processing.

 

Ok, that’s it!! now you are on your own 😉.

 

 

Let us dive in

Before DirectX 8 and the OpenGL ARB assembly language, GPU’s had a fixed way to transform pixels and vertices, called “The fixed pipeline” (mentioned above). This made it impossible for developers to change how pixels and vertices were transformed and processed after passing them to the GPU and made games looked quite similar graphics wise.

But before we start, I want to mention something about 3D meshes.

So all 3D models that you see are made up of triangles(Why? Because any plane can be break into a triangle with all vertices co-planar) with each having 3 vertices and a face. Matrices play a very important role representing. (More info)

Programs that we write whether in Java/C/C++/C# are processed on CPU, the same way shaders are processed on GPU. It is worth noting that GPUs has parallel architecture whereas CPUs process data sequentially. (More Info)

 

Recap – All 3D geometry is made up of the primitive i.e triangle which has vertices and faces.  Before shaders we have to rely on Fixed functions in which all the heavy lifting was done by CPUs and many customizations on fragment and depth cannot be done, then came shaders, which are also programs but they are executed on GPUs which are massively parallel architecture.

 

Enough! Now seriously let us do shaders…😜

As rendering a 3D mesh on a 2D screen is not that simple, as we have to calculate depths, blending, transparency lightning and so many more things, shader pipeline is divided into certain parts or types with each having something to contribute to the final output.

  1. Vertex Shader
  2. Geometry Shader
  3. Tessellation/HULL Shader
  4. Fragment/Pixel Shader
  5. Compute Shader

We will be focusing on Vertex and Fragment shaders in this series. But before we touch them a brief about the remaining three shaders.

Tessellation/HULL shader – As the name suggests it does all the tessellations related stuff in the pipeline i.e breaking the big surfaces into smaller surfaces – Triangles. It is called after Vertex Shader. In Unity rendering pipeline it acts as a Fixed-Function shader which means they are not programmable and are embedded in the hardware.

Geometry Shader – Geometry Shader takes primitive as input i.e vertex or vertices and is called after Vertex or Fixed Function Vertex Post-Processing stage. It can manipulate or alter the Geometry with the help of inputs that it has received. A point worth noting is that Vertex shader takes only single vertex as input whereas Geometry Shader can take one vertex or two vertexes (line) three vertex(triangle).

Compute Shader – This is a general purpose shader, which is used outside the pipeline.  It is not used to draw a primitive or shade a pixel. Its main role is to accelerate parts of game rendering.

 

 

I know the flowchart above is a bit too much, but that is what exactly happens behind the scene. Don’t worry I have a simpler version which we will be focusing in this series.😇

 

 

I would love to discuss Vertex Shader and Fragment Shader but before jump into these Shader types, we have to learn some important concepts like Rasterizer, Lightning Path, Transformations and basics of Vector Mathematics. So bear with me, in next post, we will dissect these topics.

Helpful Links – Triangle And Pixels

I hope this post must have helped you understand the basics of shader and its core components. We saw how a 3D mesh is rendered on a screen with help of shader and what are the stages involved. Why we don’t use Fixed Function Pipeline anymore and the very same reason motivated the graphics programmers to write Shaders i.e the customization over pixels and light.

 

If you are curious about shaders and want to know more them, then leave a comment or email me at contact@nipundavid.com

If you are interested to know more about the work I have done than do the same as above 😀

 

Please follow and like us:

Simple Android plugin for Unity3D – Part 2

In this post, we will continue from where we left in part 1, i.e. how to invoke toast from classes.jar created with android studio

Step 2 : Creating Unity3D project.

  • Open Unity3D and create new project – ‘MyAndroid’
  • Open build settings of the project, and switch to android.
  • Create a new folder – ‘Scene‘ and make an empty scene in that folder by Right Click > New> Scene. Name this scene as scene and add it in build settings.
  • Create a new folder – ‘Plugins’ in asset folder.
  • Create a new folder – ‘Android’ in Plugin folder created above.
  • Create another new folder – ‘libs’ in the android folder created above.
Note: Name should be exactly same as mentioned in order to make this work
  • Paste the classes.jar and AndroidManifest in the libs folder that we had created in part 1 of the post.

 

  • In hierarchy Right Click > UI> Button, to create a button.
  • Click on the Canvas and in inspector window go-to ‘Canvas Scalar‘ component. Click on the drop-down ‘UI Scale Mode‘ and select ‘Scale With Screen Size‘.
  • Select button under canvas, and go-to inspector window, in ‘Rect Transform‘ make selection of pivot to position the button in center of the screen
  • Increase the size of button width – 250, height – 100

 

  • Create a folder – ‘Scripts‘ in assets. And create a C# class – CallToast.cs

 

  • Open the class created above and paste below code in it.

 

An important point to note here is that the package name should be the same as mentioned in android studio project that we had created in part 1.

 using (AndroidJavaClass pluginClass = new AndroidJavaClass("com.plugin.android.simpleplugin.PluginClass"))

Also, the ShowToast() is called on UI thread as all UI elements must be called on UI thread.

public void ShowToast()
 {
      // check whether toastExample object is created or not
      if (toastExample != null)
      {
      // call toast on main thread as toast is will be shown on HUD
      // and every UI elements is called on main thread
      activityContext.Call("runOnUiThread", new AndroidJavaRunnable(() =>
      {
      toastExample.Call("showMessage", "This is a Toast message");
      }));
 }
  • Drop the script on the button, and add ShowToast() on the OnClick() of the button.

 

  • Build and run the project on your android device. Cheers!!

 

Download this project or clone it from GitHub

 

If you are curious and want to know about this project, then leave a comment or email me at nipun18david@gmail.com

If you are interested to know more about the work I have done than do the same as above 😀

Please follow and like us:

Simple Android plugin for Unity3D – Part 1

Writing plugins for android is not that hard as I used to think would be. Yes, there are certain steps that need to be followed. But overall, it’s a simple process.

This post covers how to setup android project to create a plugin for Unity3D, If you have already completed the steps in this post then you can continue reading next post – Simple Android plugin for Unity3D , Part 2.

So here are steps to write a simple plugin which will invoke a toast from android when called from C#.

Step 1: Setting up android studio project.

  • Open android studio and create a project ‘SimpleAndroidPlugin‘ with empty activity and click finish.

 

 

  • Goto File> New > New Module and add android library – ‘Simple Plugin‘.

 

 

  • Finally you android project will look something like this

 

 

  • ‘com.plugin.android.simpleplugin’ is the package where all action will happen

 

  • Create a java class name – ‘PluginClass’, in simpleplugin package by Right click> New> Java Class on the package. And paste the code as below in that class

 

  • Now about the code
    private static PluginClass instance;
    
    public PluginClass() {
        this.instance = this;
    }
    
    public static PluginClass instance() {
        if(instance == null) {
            instance = new PluginClass();
        }
        return instance;
    }

    PluginClass, as you can see is a singleton class and instance() method returns the instance of the class when called.

    public void setContext(Context context) {
        this.context = context;
    }

    setContext() is used to pass the context from the Unity3D so that it can invoke toast on that context

    public void showMessage(String message) {
        Toast.makeText(this.context, message, Toast.LENGTH_SHORT).show();
    }

    ShowMessage is called to show the toast from unity3D after all the initialization is done.

  • Here we have complete the android setup for calling toast from unity3D, all hard work is done now we have to build this project in order to create a jar and then use it in your android project.

 

  • Go to Build> Make Module ‘Simple Plugin’, after gradle is done building the jar right click on the ‘SimplePlugin‘ module in the project window and click ‘Show in Explorer‘.

 

  • Go to  SimpleAndroidPlugin\simpleplugin\build\intermediates\bundles\debug , here will find the classes.jar which we are going to use in Unity3d project to invoke toast.

 

Download this project or clone it from GitHub

 

In this post, we have seen how to create an android library i.e. classes.jar which can be used to show toast.

Please read the part 2 of this post – how to uses the lib that we have created in this post in unity3D android project.

 

If you are curious and want to know about this project, then leave a comment or email me at nipun18david@gmail.com

If you are interested to know more about the work I have done than do the same as above 😀

Please follow and like us: