这是在几个星期前工作的,但是现在我注意到我的自定义插件已经不再调用OnReward消息了.
在我的rewardcenter.cs类中,我调用plugin类将侦听器设置为该脚本所附加的gameObject(在本例中为GameObject):
public class rewardcenter : MonoBehaviour {
int counter = 0;
void Start () {
OnReward("85");
}
// Update is called once per frame
void Update ()
{
if (counter == 20) {
#if UNITY_ANDROID
PluginClass.SetRewardListener(gameObject.name);
Debug.Log("Adding Android Reward Listener: " + gameObject.name);
#endif
}
counter++;
}
void OnReward(string quantity)
{
Debug.Log("OnReward: " + quantity);
}
}
在PluginClass.cs文件中,您可以看到我如何在java插件类上调用setUnityObjectName调用,以将Unity对象设置为GameObject的名称字符串GameObject中传递的对象:
private static AndroidJavaObject pluginClassInstance = null;
private static AndroidJavaObject activityContext = null;
// pass in the GameObject that implements the OnReward method
public static void SetRewardListener(string gameObjName)
{
if (activityContext == null) {
using (AndroidJavaClass activityClass = new AndroidJavaClass ("com.unity3d.player.UnityPlayer")) {
activityContext = activityClass.GetStatic ("currentActivity");
}
}
using (AndroidJavaClass pluginClass = new AndroidJavaClass ("pluginclass.com.PluginClass")) {
if (pluginClass != null) {
pluginClassInstance = pluginClass.CallStatic ("getInstance");
activityContext.Call ("runOnUiThread", new AndroidJavaRunnable (() => {
pluginClassInstance.Call("setUnityObjectName", gameObjName);
}));
}
}
}
在java PluginClass本身以后,我们尝试使用UnitySendMessage在我们的游戏对象上调用OnReward:
public void unityEarnedReward(String quantity) {
Log.d(TAG, "unityEarnedReward: " + quantity);
if (PluginClass.getInstance()._unityObjectName != null) {
Log.d(TAG, "calling OnReward(" + quantity + ") on unityObject with name: " + PluginClass.getInstance()._unityObjectName);
com.unity3d.player.UnityPlayer.UnitySendMessage(PluginClass.getInstance()._unityObjectName, "OnReward", quantity);
}
}
我在Android Studio中的日志输出结果为:
calling OnReward(202) on unityObject with name: GameObject
但是在游戏中似乎并没有像OnReward一样调用.
只是为了踢我尝试在脚本启动时调用OnReward,最后输出:
OnReward: 85
所以我知道它的工作原理,打印到控制台执行时.
有什么想法我哪里错了?这个奇怪的事情是几个星期前工作的,但现在OnReward方法并没有执行.
编辑:
我也尝试运行它没有这样的具体的类声明没有运气:
UnityPlayer.UnitySendMessage(PluginClass.getInstance()._unityObjectName, "OnReward", quantity);
我还将我的gameObject重命名为MyCustomPlugin,但是当android代码触发时,似乎OnReward方法在链接到MyCustomPlugin的脚本上被触发.
脚本截图:
当我运行这个代码:
void Update ()
{
var unityPlayer = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
unityPlayer.CallStatic ("UnitySendMessage", gameObject.name, "OnReward", "185");
OnReward ("86");
}
我结束了两个日志消息:
04-14 10:47:47.085 10341-10354/? I/Unity: OnReward: 86
(Filename: ./artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)
04-14 10:47:47.095 10341-10354/? I/Unity: OnReward: 185
(Filename: ./artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)