Static variables vs not

Updated on October 3, 2018 in [A] Brackeys Courses
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on October 2, 2018

I’m super new to this and doing the Tower defense course.  I just got to the game over video where we change our endgame variable from a private bool to a public static bool.  Then He has to create a new start method because static variables don’t reset with resetting the scene. 

SooooI thought, well why make it static at all then?  So I decided to experiment by just making it a public bool. I mean after all what is Crtl-Z for if not to hit it as fast as you can because you messed up your entire game and hard work by experimenting with variable attributes you barely understand right?

So after hitting Ctrl-Z a bunch and getting my code back to where it worked, I looked up static vs not.  I now understand what screwed up was how the variable can be used by other scripts, and by removing the static I took away some needed functionality.  

But what I can’t get my head around is why I should use them, or I guess really the uses cases they are designed for.  Can anyone in super basic terms clear up why I would want one over the other, possibly with a use case of each?

  • Liked by
Reply
0 on October 2, 2018

Use static if there can/ should only be ONE of whatever it is you’re storing.

Things like what level you’re on can be static. There is only 1 place that it is stored, and it needs to persist through scenes.The time that has passed since a wave started. While this may not need to stay the same from level to level, at any 1 point in time, there will only ever need be 1 number that represents how much time has passed.

Things that SHOULDN’T be static, are basically anything that there can be multiple of at once, or different ones; Like enemies. Every enemy needs it’s own health, it’s own damage, it’s own name, and these don’t need to persist at all, let alone through scene changes.

  • Liked by
Reply
Cancel
0 on October 3, 2018

Much better than any other explanation I came across in my research.  Especially the part about time. thanks

  • Liked by
Reply
Cancel