Question About Singleton Pattern

Hello there,

I’ve come to a point that I started to think whether I am making a logical mistake here.

So I have a singleton class(named GameManager) and some public variables in it, lets say an Array of GameObjects. On my another script, I reach out my GameManager instance and directly use this Array of GameObjects as like reaching their child objects, using their information etc. Is it wrong to do that, performance-wise and mentality-wise? Somehow it feels wrong but I am not sure, thats why I’m asking here.

Thanks in advance.

Singletons are an easy way to make a single globally accessible access point. There has been quite a bit of complex discussion about their upsides and downsides, and there are other more complicated patterns like dependency injection that are considered “better” by many people.

However, there’s nothing fundamentally wrong with it as a technique performance wise, or at least nothing that’s going to make a significant difference in the scheme of things. It’s a much better choice than doing GameObject.Find(), which is terribly slow.

Mentality wise, it causes your code to be tightly coupled since it requires your other scripts to have knowledge of your Singleton, and the game objects that contained within your singleton. This can lead to your code becoming brittle and hard to maintain if you need to change or replace the singleton with other classes.

In your case, this is probably not a big deal, it’s probably just fine to use a singleton. Dependency Injection might be a “better” solution from a computer science perspective, but it also requires a lot more setup and understanding that probably isn’t necessary for what you’re doing.

I totally agree with @DanSuperGP. But I’d like to add something that may be easier for you to actually do / is less daunting.

You probably don’t need to have a Manager GameObject. You can totally make a static class that doesn’t extend from MonoBehaviour. Static class work a lot like Singletons, except it’s not ever instantiated. You already probably use other static methods, things like Lerp in the Mathf and Vector3 classes are examples. You can do this with variables as well. Works the same.

C# static member reference