Member-only story
Variables (C# and Unity)
In a previous article, we talked about the importance of avoiding magic numbers with variables and constants. Today we will dig deeper into variables how to use them. Before we dig in, it is important to understand that a philosophical debate about variables has been waged for years between purists and practical programmers. This article will not address those topics and instead will focus on how and when I use them. Also of importance is that the use of the term Global here is referring to a class-level variable.
Global (Class) vs Local
Variables have scope. Scope means that depending on where you declare a variable in code will impact its availability to the rest of the code. Note we are discussing a single code file here and not multiple files accessing each other; we will talk about that later. There are two primary levels of scope, Global and Local.
Global variables in C# are not genuinely global; they are technically class-level variables. This means that the variable is available to every class method, so its scope is the entire class. In the screenshot above, the variable myClassFloat is available to not only Test() but any other methods we add to the class.
myLocalFloat on the other hand has a scope that is local to Test() meaning that only code inside of Test() can access it. If we add any new…