0
votes

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:

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

When debugging, _instance is null. No ideas ?

Thank you for reading.

1

1 Answers

1
votes

You first need to instantiate the GameObject with your Xxx_Plugin attached to it. 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 pluginGameObjectas the reference or find it from anywhere with GameObject.FindObjectOfType as in your question.


Also, what you probably need is a singleton.