I know this is a controversial topic being discussed a lot , but I have not found a clear answer yet. So , there is a "Grid" in my game , which I implement it with an Array of GameObjects. This array should be accessed by different scripts in my game. My approach , is that I have a Game Manager , which is a Singleton , the array is public , and every script that needs to access it or make a change can do something like GameManager.Instance.GridArray[i,j]; .

Using singleton and public variables are heavily criticized for extensibility and coupling issues. What approach would be better for this situation ?

  • 2
    \$\begingroup\$ Right now, we know very little about how your grid is used in your game other than "like a singleton", so that makes it hard to suggest more specific solutions than "a singleton" or the usual alternatives like static classes or dependency injection. The more you can tell us about the gameplay needs this serves, the better we can target alternatives that are effective at serving those specific needs. \$\endgroup\$
    – DMGregory
    Commented Dec 6, 2020 at 23:13
  • \$\begingroup\$ @DMGregory I am using the Grid for pathfinding. In a Class Node there is a function neighbors which finds the nodes neighbors , and in some other scripts I am using width and height that are defined in the GameManager \$\endgroup\$ Commented Dec 6, 2020 at 23:18
  • \$\begingroup\$ Should the recipients of the path need to know the nodes are stored in a grid array? Or would it suffice to ask the path-giver, "Give me a path from here to there please" allowing the details of that storage to remain encapsulated rather than exposed as a public variable? \$\endgroup\$
    – DMGregory
    Commented Dec 6, 2020 at 23:21
  • \$\begingroup\$ @DMGregory The recipient of the calculated path is the GameManager. It creates an array of nodes , the calculation of the path is generated in the Pathfinding class which needs no more info than start & end node since it uses Node.Neighbors() for each step. We only need the array in the Node class. I could just use GetComponent in my Node for keeping a copy of the array but this wouldnt be much different. I dont want to make this array static. Generally , it works fine, but I would like to know if there is a better pattern. \$\endgroup\$ Commented Dec 6, 2020 at 23:38
  • \$\begingroup\$ @ThanosLoupas When only one object uses the grid (the GameManager) why not give the GameManager a reference to the grid it is supposed to use? Then you don't need to make the grid a singleton. \$\endgroup\$
    – Philipp
    Commented Dec 7, 2020 at 0:35


You must log in to answer this question.

Browse other questions tagged .