In previous blog, I have covered how to handshake Native Android code with Unity3D. The example shown therein is pretty simple: how to call a java function in C#!
In this blog, I am trying to step one more stride further: to create and use an Android View in Unity3D. The example shown here is an Android ImageView, however, this approach is generally applicable to all kinds of Android Views, ViewGroups and custom views.
Use Android ImageView in Unity3D
First, create an Android Library project with Android Studio. I will not repeat this process and snapshots are available in my previous post.
Create a new class called “Utils”, add below code snippet:
In this class, we defined a few static functions to add a FrameLayout, an ImageView etc to an Android Activity, together with a static function which add an image whose resource is defined as R.drawable.android, which is saved in the lib_project\src\main\res\drawable-xxhdpi folder.
Next, build the library project and we can get an aar file in the folder lib_project\build\outputs\aar\;
Copy this aar file to the Unity3D project, anywhere in the Assets folder or its subfolders;
Create a MonoBehaviour C# script in U3D project as shown below, attached this script to the Main Camera or any game object:
In these functions, the Android Java function in the Utils class is called in the C# Start() function, specifically, the Utils.AddExampleImageView() function is called!
Note that in order to call this function, we need to get the Android Activity and pass it as the 1st argument. To implement this, we created a C# static function called GetAndroidActivity() as shown in the code snippet above.
Build the U3D project and run it on an Android device! Wow, it worked now!
For the source code, please clone this GitHub Repo. Don’t forget to star it!
Filed under: Android, Programming, Unity 3d Tagged: addin, android, android view, embed, example, how to, plugin, Unity
