- Home /
In which cases I should use static?
I did some research and people always say there are some places that static is unavoidable or just the better choice but it most of the time it could be avoided. I have plenty of static vars & methods in my project so I got very suspicious. Simple examples when I'm using static are InputHandler.JustReleased(), CollidersManager.DeactivateColliders(GameObject go), SortingLayerManager.IsTopmost(GameObject go) and so on. I know I can just check if(Input.touches == 0) || Input.GetMouseButtonUp and so on but I like it more when it's all at 1 place.
Question: For what situations should I use static and for what I should definately avoid it? Consider singleton part of the question as well.
P.S. Don't give me the smalltalk like "when you want to have only 1 isntance" and bla bla just to get votes.
I agree with your first sentence: it's what I learned in computer school, and what I find works in practice: statics are a hack, to be used as a last resort. Which does not mean never. If you can look at your cat and say "using a static here is crud, but the other stuff I thought of is worse."
Statics were trendy here about a year(?) ago, and a lot of people used them like a garnish. It's like how you learn a new word and try to use it everywhere, even if it isn't really appropriate. Then there were a lot of "killing one enemy kills all" Qs, caused by using them.
@Owen Reynolds , very nice explanations! Still curious though, where would you use (static && singleton) if use them at all?
Answer by Digital-Phantom · Mar 03, 2015 at 01:31 PM
I can give a couple of examples based on my own works. I use static for keeping scores, lives and health stats that I need to carry over from one scene to another (in conjunction with a game object and DoNotDestroyOnLoad game objects)
A use where I found static to be problematic was where I wanted cannons to fire just one cannon ball at a time. I used a static variable to keep track of 'ifCannonBallExists' which actually worked fine. UNTIL I placed more than one cannon in my scene and all the cannons then looked for this variable and only one would fire because they all thought the cannon ball existed.
So I guess any situation where more than one object needing the same information is definitely a time static is 'not' good.