I am making a Grid - Turn based game, something like Final Fantasy Tactics, Fire emblem, or Xcom.
I just noticed, that I use a lot of singletons, and was wondering if I went a little overboard.
Specifically:
-
My “Grid” script, which stores the matrix itself and provides methods for pathfinding and highlighting tiles, is singleton.
-
My “HudManager” script, which stores references to all of my GUI buttons, is also singleton. The idea is that the HudManager knows which player is currently selected, and will call methods referencing that script when a button is pressed.
-
I was thinking of making an observer class called MouseRayObserver. The idea behind is for it to be the only class that raycasts the mouseìs position, and inform its observers when the mouse button is pressed on an object. This class, in my mind, is also a singleton.
Am I going overboard with singletons? What logical thinking should I apply to decide if a class should be singleton?
Thanks in advance
Are you using to many singletons??
Probably not, i guess the point is whats the difference between a singleton representing a singular existence of an instance of an object and ensuring that just ONE instance of a non-static object/class get created, other then patterns and wise design decisions, not a whole bunch. What you’re doing with singletons can be done with instances of classes if you want.
Generally people using Unity don’t quite get the order of operation or haven’t grasped the ability to get references of GameObjects/MonoBehaviour/Component throughout the scene. This is generally why i think we see more FindGameObjectWithTag invocations instead of scoping down to the GameObject and caching the Component by type. But wouldn’t it be easier to contain everything in on bucket?
Under those conditions they tend to seek out the one class/instance to rule them all and a bunch of static instances start existing to represent these classes and members.
On the surface it seems like there’s some love story going on. You can invoke(get/set/whatever) a member from the static instance on a class(class-member) and get all the values you want, no GetComponent, nothing, it’s dreamy at first.
Later in life you will start to understand that there should be limited uses for this implementation and it’s actually preventing you from doing some pretty sexy object oriented fluffer-butter in your code. This is when you will decide to learn more about the engines you use and the languages they rely upon.
there is no real rule about the use of “singleton” classes .
At the end it’s just a class that exposes a reference to his application , therefore , unless they face particular reasoning , should not lead to unpleasant consequences .
You must use the singleton when you need access to the class from many different classes , relieving you from the duty of to reference the instance , or search the instance with functions like FIND.