1
\$\begingroup\$

Ok the title might be a bit confusing but what I want to do is make a getter that returns the class, exactly like unity does with the camera.current.

You should just be able to go class.current and get the running instance of the class but I have no idea how to do this as it would most likely be a static method but how would you return the class form a non static class without some sort of out of class variable? or do you have to make the class static?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ if(instance == null) { createTheInstance(); } return instance; \$\endgroup\$
    – OMGtechy
    Commented Mar 23, 2016 at 20:58
  • \$\begingroup\$ ...or oneliner: return instance ?? createTheInstance(); \$\endgroup\$
    – wondra
    Commented Mar 23, 2016 at 21:31

1 Answer 1

2
\$\begingroup\$

You just need a static variable of the same type as the containing class. Then you set that static variable to your instance of interest. For Camera.current, that would be whatever camera is currently in use. Or Camera.main is whatever camera is tagged with 'MainCamera'. You decide what conditions result in the static variable being set. For example below, if you just had one instance in your game, you can set it in the Start method.

public class MyScript : Monobehaviour {
    public static MyScript myInstance;

    public void Start() {
        myInstance = this;
    }
}

You'd access this instance with MyScript.myInstance

Or if you didn't want it to be a script attached to an object, you can easily do something similar with a static code block:

public class GameManager
{     

    public static GameManager instance;     
    static GameManager()
    {         
         instance = new GameManager();     
    }

    public GameManager() {
         //initialize stuff here
    }
}

Or even stuff if all into a getter:

public class GameManager
{     
    static GameManager _instance;
    public static GameManager instance {
        if(_instance == null)
        {
            _instance = new GameManager();
        }
        return _instance;
    };     

    public GameManager() {
         //initialize stuff here
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .