The scope of a variable is the area or length of code that can be used. In a sense, scope is a variable's lifetime. There are two primary types of scope that we use with regularity in C#:
- Local scope: These variables are defined within a method or inside the block of a method. Local scope variables defined within a method are released when the method ends.
- Class-level scope: All the names defined inside the current class, aside from local names, are said to be local to that class. This means that the class-level variables live as long as the class is active.
Code blocks are generally the means of defining a scope and are marked with curly braces {}:
public class ScopeExample: MonoBehavior { public int dododododo = 3; public int mahna = 2; public int mahnah = 5; void MethodScope(int never, int again) { int methodScopeVariable; methodScopeVariable = (never + again +dododododo + mahna + mahnah); Debug.Log(methodScopeVariable); } void Update() { MethodScope(mahna, mahnah); // Answer 17 Debug.Log(dododododo); //answer 3 Debug.Log(mahna); //answer 2 Debug.Log(mahnah); //answer 5 Debug.Log(methodScopeVariable); //error out of scope. } }
As you can see here, we declare three class-scope variables. We also have a method that gets called. During the process, a variable is created. Due to methodScope, the variable is limited to the method that created it; so, when Debug.Log (methodScopeVariable) is called, we are outside of its scope, which causes an error. Enjoy this earworm!