Get applicationContext from Unity 3d
本文关键字:3d Unity from applicationContext Get | 更新日期: 2023-09-27 18:20:16
我正在为unity 3d编写一个android插件,我的问题是初始化我需要将applicationContext传递给一个方法。所以我的MyPlugin.cs
在下面
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});
}
}
在android UnityPlugin.java
类中,我有
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");
}
}
}
并且我一直得到CCD_ 3。从团结活动中获得AppilcationContext
的正确方法是什么?
首先,检查pluginClass是否为空
if(pluginClass == null) Debug.Log("plugin class is null");
如果是,请确保您正在创建具有正确字符串参数的新AndroidJavaClass。
接下来,我不知道为什么要传递一个Activity的数组,而不是只传递Unity的上下文。试试这样的东西:
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
pluginClass.CallStatic("initialize", context);
您还需要以以下方式更改插件端:
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();
}
}
}