2

I am developing an Android plugin for Unity and I am wondering if there is a way in the Android code to call a Unity C# method that returns a value and get this value.

Of course this will NOT work but is there a way, tips, tricks to achieve something like this:

String myReturnedString = UnityPlayer.UnitySendMessage("MyGameObject", 
                          "ReturnThisString","hello");

Many thanks for your help.

2 Answers 2

3

In Android:

int Times_Called;
public  int Get_Times_Called()
{
   Times_Called += 1;
   return  Times_Called;
}

In Unity

 AndroidJavaClass Java = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
 AndroidJavaObject AndroidActivity = Java.GetStatic<AndroidJavaObject>("currentActivity");
 int Times_Called = AndroidActivity.Call<int>("Get_Times_Called");
        Debug.Log("Get_Times_Called: " + Times_Called);
Sign up to request clarification or add additional context in comments.

Comments

2

One way is to have a method in your Unity program that communicates with your Android application through a method in your Android app, by using AndroidJavaObject.Call in your Unity class.

e.g. You have this method in your Android application.

AndroidActivity.java

String stringFromUnity = "";

public void setStringFromUnity(String input){
    stringFromUnity = input;
}

Then in your Unity script (I am using C#).

UnityScript.cs

// Get the UnityPlayer class
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

// Get the current activity
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");

// Call the setStringFromUnity method from Android Activity
activity.Call("setStringFromUnity", "Here is a string for you, Android");

OR we can set the String directly using the AndroidJavaObject.Set method.

// Set the String directly provided the String is public
activity.Set<string>("stringFromUnity", "I set your String directly, hah!");

Hope this helps.

For reference, you can search for "Unity Plugins for Android" or take a look at Unity documentation at this link.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.