Performance impact of keeping all instances of a game in a single script

Hi there,

I did some research, but couldn’t find an answer for it, and it’s been bugging me for some time now. Anyway, please forgive the noob question, but here it is: Is more performant to use a script attached to an empty game object, which has all the variable instances the game would use, and then have all the other scripts use the instances from that script?

Let me try to be more clear:
I am trying to clean up a code for a game I’m working on using the SOLID principles, and in most scripts that I have, I noticed that in the awake() or start() function, I use instances such as Camera cam = Camera.main, or GameObject player = GameObject.FindGameObjectWithTag(“Player”), and so on. So I thought instead of having the instance of cam and player (and other variables I use in the game) repeated in different scripts, why not have them in a single script called ObjectInstances (which has only the awake function), so that other scripts can use the needed variables from this ObjectInstances script.
This way, all the game variables would have a single instance in the whole game, and the ObjectInstances script would have an instance once in all the other scripts.
Now, that being said, here are my concerns:
-Is this way really more performant than having in the game scripts all the instances they need, even if they are repeated (between different scripts)?
-Are there some foreseeable problems that you know this way of coding will create?
-What about the impact on the memory usage?
Any feedback or help would be greatly appreciated,
Thank you :slight_smile:

This is definitely more performant due to the fact that you are not using as many GetComponent calls and you are creating less instances of variables that are identical. It’s like creating two objects that do the same purpose instead of just one. This is more efficient.


However, this can lead to problems down the line, where multiple scripts are changing a variable and other scripts are reading that value. This creates a lot of bugs and spaghetti-code issues, where you are retrieving a value at some point in time and it returns a completely different value than what you expected. This is easily solved using multiple fresh new instances of that variable, for that purpose.


In summary, if you are putting read-only variables in a static script, so you only need to create one instance of them, this is great performance-wise. However, if you put read/write variables in the same place, the code flow can get messy and confusing as to what scripts are changing and reading this variable at one time. If that makes sense.