Hey There,
I’m rewriting some of my code so that a bunch of instance variables are now stored as static variables in a static class called StaticVariables. For example: one of these static variables is a bool PlayerGrounded, which is updated every frame in my main character’s monobehaviour script. Before switching variables to this static class design, many scripts in my game needed check her grounded state, ie: GameObject.Find("Player") —> GetComponent<PlayerScript>().PlayerGrounded (or some other assignment method). Now they can all just check StaticVariables.PlayerGrounded, which is what I was going for and so far works great.
My worry is that this approach of updating a static variable of a static class inside another script every frame is less efficient than using a local variable like I did before. So far I haven’t noticed any issues, but I just want to make sure before I get too deep in this direction. Any thoughts?
As best practice you should be updating your playerGrounded in the Player class, it makes no sense to update your player by using the ground or an external class, there are multiple reasons as to why you want the logic of the class to drive itself (How are you going to tell AI that it’s grounded…)
As for your concern there is no difference if you update a static or a instanced variable every frame, In theory, a static should perform slightly better than an instance, all other things being equal, because of the extra hidden this parameter.you’re still going to have the exact same hit to preformance as you would if it was a instanced (NOT USING GAMEOBJECT.FIND) of the variable. Using Gameobject.find will kill your performance on every tick!
A static variable comes into existence before execution of the static constructor, this is why you cannot instance new ‘Instances of it’ at runtime, since you’re using a single bool in this case you should use a static, I would even go so far as to suggest a singleton in your case if you continue to use external classes to drive other classes.