【问题标题】:Create Android plugin with Unity (C#)使用 Unity (C#) 创建 Android 插件
【发布时间】:2014-09-12 09:04:32
【问题描述】:

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

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
        }


    }

这是我第一次使用 unity,我不确定它是如何工作的。在我的脚本中,我想获取我的插件的实例。正如官网所说,扩展 MonoBehaviour 的类不能被实例化,应该被称为 GameObject:

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

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

感谢您的阅读。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您首先需要实例化带有Xxx_Plugin 附加到它的游戏对象。要么:

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

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

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

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


    另外,您可能需要一个singleton

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 2013-10-26
      相关资源
      最近更新 更多