- Home /
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.
Answer by DanSuperGP · Jan 22, 2015 at 08:20 PM
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.
Thank you for you comment and your suggestions. I've experienced aforementioned problem about changing the singleton with other classes but that's not a big deal for me at this time because the project I'm working on is not a big one and I can deal with changes since it compromises small amount of scripts. Thank you again for your fast reply.
Answer by carrollh · Jan 22, 2015 at 08:29 PM
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.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Singleton and DontDestroyOnLoad question 1 Answer
Singleton that can react to game events 2 Answers