Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get applicationContext from Unity 3d

I am writing an android plugin for unity 3d, my problem is for initialize I need to pass applicationContext to a method. So my MyPlugin.cs is like below

using UnityEngine;
using System.Collections;

public class MyPlugin : MonoBehaviour {

void Awake () {
    Debug.Log ("awake");
    Initialize ();
}

public static void Initialize()
{
    AndroidJavaClass playerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject activity = playerClass.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaClass pluginClass = new AndroidJavaClass("com.mycompany.product.UnityPlugin");
    pluginClass.CallStatic("initialize", new object[1] {activity});
}
}

and in android UnityPlugin.java class I have

public class UnityPlugin extends Plugin {
    static public void initialize (Activity unityActivity){
        try {
           MyApp.initialize(unityActivity.getApplicationContext());
        } catch (NullPointerException e){
           Log.d("unity", "null pointer exception");
        }
    }
}

and I get NullPointerException all the times. what is the correct way to get AppilcationContext from unity activities?

like image 770
nfarshchi Avatar asked Nov 03 '15 10:11

nfarshchi


1 Answers

First, check if pluginClass is null

if(pluginClass == null) Debug.Log("plugin class is null");

If it's make sure you're creating new AndroidJavaClass with proper string argument.

Next, I'm not sure why you're passing array of one Activity instead of passing just Unity's context. Try something like this:

AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
pluginClass.CallStatic("initialize", context);

You'll also need to change plugins side in following manner:

public class UnityPlugin extends Plugin {
    static public void initialize (Context unityContext){
        try {
            MyApp.initialize(unityContext);
        } catch (NullPointerException e){
            Log.d("UnityPlugin", "Null PTR Exception");
            e.printStackTrace();
        }
    }
}
like image 147
Rafal Wiliński Avatar answered Oct 19 '22 03:10

Rafal Wiliński