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
}
}
if(instance == null) { createTheInstance(); } return instance;
\$\endgroup\$return instance ?? createTheInstance();
\$\endgroup\$