UnitySendMessage(AGameObject, MethodName, Message to Send)

By Jc

This function accpets 3 parameters. The first one refers to the game object, your plugin wants to talk. For instance if your game object is an imagetarget then in the first parameter you would type its name. The second name calls the function you want Unity to call. In order this to work, the function name must be in a script which is attached to the gameobject in Unity, otherwise error message will occur. Unity will find automatically the script with the function i want if the first two parameters are true. Finally, we pass the string we want to send to the function we called previously, using the third parameter. So, that’s the basic idea and the process required for the communication to work. Simple right?


A simple real life example


In theory it seems pretty straight and easy. Thats why below i wrote a simple example of how to use it in your code.


package gr.ceid.upatras;


import com.qualcomm.QCARUnityPlayer.QCARUnityPlayer;

import android.content.Intent;

import android.os.Bundle;


public class Binding extends com.qualcomm.QCARUnityPlayer.QCARPlayerActivity {


@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

}


public static void buttonClicked() {


QCARUnityPlayer.currentActivity.runOnUiThread(new Runnable() {

public void run() {

                    String message = generateMessage();

                    sendMessageToUnity(message);

}

});

}


      private static String generateMessage()

{

Random randomGenerator = new Random();

int randomInt = randomGenerator.nextInt(100);


return "Hey Unity! here's your random integer you asked, "+randomInt;

}


    public static void sendMessageToUnity(String message)

{

Log.i("SendMessageToUnity","Called: "+name);

QCARUnityPlayer.UnitySendMessage("ImageTarget","MessageFromJavaToUnity!",message);


}

}

 

I use the QCARUnityPlayer object to call UnitySendMessage because i am creating an augmented reality application and i use the Vuforia SDK. If you are creating a simple plugin between Unity and Android then you should use the UnityPlayer object instead.


In the code above, i am calling a function called MessageFromJavaToUnity which exists in a script that is attached in my gameobject (1st parameter). My gameobject in this example has the name ImageTarget. 

After you successfully pass your string paremeter to Unity, you can use it how ever you want in your script.