I’m very confused when it comes to communicating between Unity (C#) scripts and my Java android activity.
To send a message from Java to Unity I just call the static method UnityPlayer.UnitySendMessage and this works fine.
Is there not some easy way to do the reverse? All the ‘tutorials’ I’ve seen talk about having to build a plugin first (why???), and they aren’t exactly clear on the process of doing so.
So I have two questions:
Is there any equivalent unity/c# of UnitySendMessage, that will deliver a message to UnityNativePlayerActivity to handle?
If not, what is the process for building a plugin? Do I need to define all methods to be called in that plugin, or is it some kind of blank skeleton project? (all the documentation I’ve seen seem to involve creating pretty empty java projects)
In order to call from Unity (C# code) to the Java VM (UnityNativeActivity, etc), you use the AndroidJavaObject and AndroidJavaClass classes.
The reason the documentation mentions that you have to build a Java plugin, is that the code you’d like to call probably doesn’t exist yet (they assume it is some custom functionality that you’re going to add and call to from your C# code).
If, however, you’d like to call some existing Java methods that exist on the Activity class, you can do that without building a plugin:
For example, the Activity class in Android exposes a public getTaskId() method. If you want to call it, you don’t need to build a plugin:
using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
using (AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"))
{
// Call the getTaskId() method
int result = jo.Call<int>("getTaskId");
}
}
The UnityPlayer class exposes a static currentActivity field with the game’s main activity. Once you get a reference to it, you can use it to call a method on it.