1
\$\begingroup\$

I am trying to call a method within a Unity app from an Android activity by using UnityPlayer.UnitySendMessage. I am getting the error "SendMessage: (ObjectName) not found!".

I've confirmed the following:

  • There is a GameObject in the scene with the name of (ObjectName)
  • The script is attached to said GameObject
  • The C# class and filename are named the same as the GameObject
  • The C# method attempting to be called is public

Here are some code snippets to give an idea as to how this is built:

Unity

using UnityEngine;
using System.Collections;

public class GCMHookBridge : MonoBehaviour {
    void Start () {
#if UNITY_ANDROID
        AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject currentActivityObj = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity");

        var mainActivityClass = new AndroidJavaClass("com.unity.unitygcmreceiver.MainActivity");
        mainActivityClass.CallStatic("LaunchActivity", currentActivityObj);
#endif

    }

    public void sendGCMIDToServer(string regid) {
        Debug.Log("Unity Regid: " + regid);
    }
}

Java

The Java class being called here extends Activity. I am not extending UnityPlayerActivity because there is already an Android plugin that does this.

The Unity code above is calling this static method:

public static void LaunchActivity(Activity root) {
    Intent intent = new Intent(root, MainActivity.class);
    root.startActivity(intent);
}

From there the Activity runs as expected until it tries to interact with the Unity instance.

I do this as so:

  1. An AsyncTask is created
  2. UnityPlayer.UnitySendMessage("GCMHookBridge", "sendGCMIDToServer", registration_id) is called

I've wrapped #2 with com.unity3d.player.UnityPlayer.currentActivity.runOnUiThread.

I've called the UnitySendMessage method outside of the AsyncTask thread.

My suspicion is while my Android activity is running, the Unity activity is not, and therefore inaccessible. But from my debugging it looks like the async task thread is allowing the Android activity to exit, and the main unity thread to resume.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.