A Unity design pattern to access singletons without typing
.instance
<aside> 🚧 Heads up! This post is not about:
It's just about typing less characters if you do use singletons already.
</aside>
In Unity code, you're likely to eventually end up using singletons: unique instances of a class that you want to access from anywhere without setting up the dependency manually.
However, unlike static classes, singletons are instanced, which means that to access them you'll have to point to an object reference traditionnally called instance
. This is totally normal but also totally annoying for lazy (read: all) programmers who like to save on keystrokes whenever possible.
For example, in its simplest form, a C# singleton looks somewhat like this:
class GameManager
{
public static GameManager **instance** { get; } = new GameManager();
public int score { get; set; }
}
And to access the singleton instance from elsewhere, you'd type:
class Goal : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
GameManager**.instance**.score++;
}
}
. i n s t a n c e
? Really? That's 9 barbaric keystrokes that require manual labour! Let's fix it.
If GameManager
was declared as a static class, we'd avoid having to type .instance
:
**static** class GameManager
{
public **static** int score { get; set; }
}
Then accessing its members would be shorter:
class Goal : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
GameManager.score++;
}
}
This may be tempting at first, but it's either:
MonoBehaviour
, then you just can't make it static;