Game Development Reference
In-Depth Information
Variable scope
Each variable is declared with an implicit scope. The scope determines
the lifetime of a variable, that is, the places inside a source file where
a variable can be successfully referenced and accessed. Scope is
determined by the place where the variable is declared. The variables
declared in code sample 1-1 have class scope, because they are declared
at the top of a class and outside any functions. This means they can
be accessed everywhere throughout the class, and (being public) they
can also be accessed from other classes. Variables can also be declared
inside specific functions. These are known as local variables, because
their scope is restricted to the function, that is, a local variable cannot
be accessed outside the function in which it was declared. Classes and
functions are considered later in this chapter.
More information on variables and their usage in C# can be
found at http://msdn.microsoft.com/en-us/library/
aa691160%28v=vs.71%29.aspx .
Conditional statements
Variables change in potentially many different circumstances: when the player
changes their position, when enemies are destroyed, when the level changes, and so
on. Consequently, you'll frequently need to check the value of a variable to branch the
execution of your scripts that perform different sets of actions, depending on the value.
For example, if PlayerHealth reaches 0 percent, you'll perform a death sequence, but
if PlayerHealth is at 20 percent, you might only display a warning message. In this
specific example, the PlayerHealth variable drives the script in a specified direction.
C# offers two main conditional statements to achieve a program branching like this.
These are the if statement and the Switch statement. Both are highly useful.
The if statement
The if statement has various forms. The most basic form checks for a condition
and will perform a subsequent block of code if, and only if, that condition is true .
Consider the following code sample 1-2:
01 using UnityEngine;
02 using System.Collections;
03
 
Search WWH ::




Custom Search