使用Unity创建Android插件(C#)

时间:2014-09-12 09:04:33

标签: c# unity3d

我创建了一个简单的统一插件(参见下面的代码)

using UnityEngine;
using System.Collections;

    public class Xxx_Plugin : MonoBehaviour {

        static AndroidJavaObject m_plugin;
        static GameObject m_instance ;
        public static string objEvent = "" ;

        //Awake is called when the script instance is being loaded.
        public void Awake(){

            m_instance = gameObject;
            objEvent = gameObject.name;

            //Makes the object target not be destroyed automatically when loading a new scene.
            DontDestroyOnLoad(transform);

            #if UNITY_ANDROID
            inst();
            #endif

        }


        void inst ()
        {
            #if UNITY_ANDROID
            try {
                m_plugin = new AndroidJavaObject ("jp.xxx.plugin.PNUnityPlugin_xxxx");
            } catch{}
            #endif
        }



        //buy an item
        public void BuyItem (string idItem)
        {

            Debug.Log("enter in 'BuyItem' method" );

            #if UNITY_ANDROID

            // If network is not reachable.
            if (Application.internetReachability == NetworkReachability.NotReachable) {
                Debug.Log("network is not reachable.");
            }else{ 
                if (m_plugin == null)
                    inst ();
                try {
                    m_plugin.Call ("Click", new object[]{idItem});
                } catch { }
            }
            #endif
        }


    }

这是我第一次团结,我不确定是否真的理解它是如何运作的。在我的脚本中,我想获得我的插件的实例。正如在官方网站上提到的那样,扩展MonoBehaviour的类无法实例化,应该被称为GameObject:

Xxx_Plugin _instance = GameObject.FindObjectOfType (typeof(Xxx_Plugin)) as Xxx_Plugin;
_instance.BuyItem("tudo04");

调试时,_instance为null。没有想法?

感谢您的阅读。

1 个答案:

答案 0 :(得分:1)

首先需要在附加Xxx_Plugin的情况下实例化GameObject。之一:

  • 在层次结构中创建一个游戏对象并将您的课程拖到它上面,或者

  • 在脚本(official documentation)中执行此操作:

    var pluginGameObject=new GameObject("XXX Plugin GameObject");
    pluginGameObject.AddComponent<Xxx_Plugin>();
    

现在使用pluginGameObject作为参考,或者在问题的GameObject.FindObjectOfType处找到它。


此外,您可能需要的是singleton