繁体   English   中英

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

[英]Create Android plugin with Unity (C#)

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

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为空。 没有主意吗?

感谢您的阅读。

您首先需要实例化Xxx_Plugin附加Xxx_Plugin 或者:

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

  • 使用脚本( 官方文档 )进行操作:

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

现在使用pluginGameObject作为参考或从任何地方找到它GameObject.FindObjectOfType在你的问题。


另外,您可能需要的是单例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM