I have a game which has lot of C# scripts in Unity. From one of the scripts I call android Java code which works fine using AndroidJavaObject. But I am not able to call a C# function back(needs to be a callback) from Java Code.
Went through this link and able to create a simple app which contain one C# file
http://forum.unity3d.com/threads/78598-Android-Plugin-Call-C-from-Java
My C# file contain function =>void JavaMessage(string message)
Was able to call this using => UnityPlayer.UnitySendMessage(“Main Camera”, “JavaMessage”, “Message to send”);
But when i tried calling same thing in complete game project which contains Main Camera, GUI2D, Preloads etc and many C# script none of the below was able to make a call to C# function
UnityPlayer.UnitySendMessage(“Main Camera”, “JavaMessage”, “Message to send”);
UnityPlayer.UnitySendMessage(“CallJavaCode”, “recieve”, “Message to send1”);
CallJavaCode is C# file name or class name.
C# Code
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System;
public class CallJavaCode : MonoBehaviour {
private static AndroidJavaObject _admobPlugin;
void OnGUI ()
{
if (GUI.Button(new Rect (15, 125, 450, 100), "Push button To call Java code"))
{
Screen.sleepTimeout = SleepTimeout.NeverSleep;
Debug.Log("BeforeCalling Java Function : getURL");
using(var pluginClass = new AndroidJavaClass("com.example.helloworld.TestApp"))
_admobPlugin = pluginClass.CallStatic("instance");
_admobPlugin.Call("getURL","Shashank");
Debug.Log("After Calling Java Function: getURL");
}
}
void recieve(string message){
Debug.Log("On recieve message: getURL");
Debug.Log(message);
}
}
Java Code
public class TestApp {
public static TestApp m_instance;
private UnityPlayer mUnityPlayer;
public static TestApp instance(){
if(m_instance == null)
m_instance = new TestApp();
return m_instance;
}
private TestApp(){
}
private void getURL(String message){
Log.d("Unity","This is onbuttonclickresponse =>"+ message);
UnityPlayer.UnitySendMessage("Main Camera", "JavaMessage", "Message to send");
}
}