简体   繁体   English

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

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

I have created a simple plugin for unity (see code below) 我创建了一个简单的统一插件(请参见下面的代码)

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
        }


    }

It's my first time with unity, and I am not sure to really understand how it works. 这是我第一次团结一致,我不确定是否真正了解团结的运作方式。 In my script, i'd like to get instance of my plugin. 在我的脚本中,我想获取我的插件的实例。 As mentioned on the official site, class that extends MonoBehaviour cannot be instantiate, and should be called thought the GameObject: 如官方网站上所述,扩展MonoBehaviour的类无法实例化,应在GameObject的基础上进行调用:

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

When debugging, _instance is null. 调试时,_instance为空。 No ideas ? 没有主意吗?

Thank you for reading. 感谢您的阅读。

You first need to instantiate the GameObject with your Xxx_Plugin attached to it. 您首先需要实例化Xxx_Plugin附加Xxx_Plugin Either: 或者:

  • create a gameobject in the hierarchy and drag your class to it, or 在层次结构中创建一个游戏对象并将您的类拖到该对象上,或者

  • do it in a script ( official documentation ): 使用脚本( 官方文档 )进行操作:

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

Now use the pluginGameObject as the reference or find it from anywhere with GameObject.FindObjectOfType as in your question. 现在使用pluginGameObject作为参考或从任何地方找到它GameObject.FindObjectOfType在你的问题。


Also, what you probably need is a singleton . 另外,您可能需要的是单例

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

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