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:

Leave a Reply