Is it possible to create a & ldquo; global & rdquo; class instance in Unity?

advertisements

Sorry for the silly question, I'm a newbie in Unity scripting.

I need to create a class instance which it need to be shared and accessed by the components in any scene.

I could easily create a static class and use it in the component scripts, but my class have heavy network and processing, and since I need to process it only once, it would be nice to create only a single instance.

Is it possible to do something similar to that? For example:

// The class which I need to create and share
public class DemoClass {
     MyExampleClass example;
     public DemoClass (){
            example = new MyExampleClass ();
      }
     public MyExampleClass GetClassInstance(){
            return example;
      }
 }

// The "Global Script" which I'll instantiate the class above
public class GlobalScript{
    MyExampleClass example;
    public void Start(){
         DemoClass demoClass = new DemoClass();
         example = demoClass.GetClassInstance();
     }

     public MyExampleClass getExample(){
         return example;
      }
  }

  // Script to insert in any component
  public class LoadMyClass : MonoBehaviour {
      public void Start(){
          // this is my main issue. How can I get the class Instance in the GlobalScript?
          // the command below works for Static classes.
          var a = transform.GetComponent<GlobalScript>().getExample();
       }

Any hint on this would be very appreciated.

Thanks.


At a simple level, it would seem that a singleton pattern would be the way to go (as mentioned above). While not from an official Unity resource, here is a link to a tutorial and also a code example that is documented fairly well.

http://clearcutgames.net/home/?p=437

Singleton Example:

using UnityEngine;

public class Singleton : MonoBehaviour
{
    // This field can be accesed through our singleton instance,
    // but it can't be set in the inspector, because we use lazy instantiation
    public int number;

    // Static singleton instance
    private static Singleton instance;

    // Static singleton property
    public static Singleton Instance
    {
        // Here we use the ?? operator, to return 'instance' if 'instance' does not equal null
        // otherwise we assign instance to a new component and return that
        get { return instance ?? (instance = new GameObject("Singleton").AddComponent<Singleton>()); }
    }

    // Instance method, this method can be accesed through the singleton instance
    public void DoSomeAwesomeStuff()
    {
        Debug.Log("I'm doing awesome stuff");
    }
}

How to use the singleton:

// Do awesome stuff through our singleton instance
Singleton.Instance.DoSomeAwesomeStuff();