Is singleton pattern the appropriate way to get prefab references to the scripts that spawn them?

I’m working on my UI, and running into a lot of cases where aggressively decoupled classes with very narrow scope need to instantiate a fairly wide variety of prefabs. The inventory screen, for instance, needs some way to locate the icon prefab for every single item type, but it doesn’t actually need knowledge about the item system- all it needs to do is retrieve a series of IDs and turn those into the desired prefab.

Thus far, I’ve been handling this by creating a Database singleton with a dict<int,GameObject> for every category of prefab I need to store, and giving it publicly-accessible GetPrefab methods that take an ID, and return a gameobject of the desired type.

This has the effect of coupling everything to my database, but since the database doesn’t do anything besides associate IDs with gameobjects, I don’t see any architectural issue with this- have I hit on a generally acceptable solution, or is this something that’s going to bite me in the rear end as the complexity of the codebase scales up?

That’s the method I ended up using for my RPG project, and it hasn’t caused me any problems thus far.

“Class A needs to create an instance of Class B based on some data that it has. It doesn’t need to know exactly what type of class B its creating. in essence, Class A wants to remain decoupled from the Class B’s concrete implementation”

That totally sounds like a job for the Factory pattern. Factorys are sometimes implemented as singletons, but its also possible that you can write several factorys and then inject and use them abstractly. That way the implementing class simply uses the factory that it was set to use from the inspector, without it knowing exactly which factory that its using, or the items the factory is creating for them.

I’m a big fan of using ScriptableObjects for this sort of thing. You can link all of your icon prefabs in the editor itself and then use your ScriptableObject as a sort of factory. Then just link the ScriptableObject to the UI object in the inspector.

1 Like