So I have lately been doing something like this
public class MyClass
{
static public MyClass staticThis;
void Awake()
{
staticThis = this;
}
void AllMyShit()
{
}
void Whatevs()
{
}
}
And then from anywhere in my entire game I can access the last created instance of MyClass via MyClass.staticThis
This is seeming really useful and easy to me… but it seems almost too easy. Am I doing something with this practice that is generally a bad idea that I shouldn’t be doing?
Generally, you declare variables to be private and have functions to set and get that variable. If it’s not an important variable, then it doesn’t matter.
One potential problem is that “staticThis” won’t necessarily be available in other scripts’ Awake functions, unless you make use of script execution order. Also, it’s public read/write, which means it could potentially be changed, which isn’t likely, but you can still kill two birds with one stone:
public class MyClass : MonoBehaviour {
static MyClass _staticThis;
static public MyClass staticThis {
get {
if (_staticThis == null) _staticThis = FindObjectOfType(typeof(MyClass)) as MyClass;
return _staticThis;
}
}
// other stuff
}
–Eric
Thank you eric, as always your help is greatly appreciated.