Game Development Reference
In-Depth Information
Exploring Functions
Variables are pretty much useless unless you do something with them. This is where functions come
into play. Functions come in a few different varieties, differentiated by how and when they are called.
Some are called or evaluated continually. Some are called only when triggered by certain events, and
some are called on demand from inside other functions. Their contents contain instructions to carry
out the functionality in your game.
Introducing the Start Function
The two most common functions, and therefore included in the C# template, are the Start and
Update functions. Let's begin by examining the Start function. It is one of a small number of
functions that are called only at the start of the game or when an object is instantiated or created
during runtime (e.g., when it is started). The Awake function, another, is called before the Start
function and is often where you will have to find and identify objects that are inactive at the start of
a game, You will use it later in the topic as the game progresses. Generally, the Start function is the
one you will use most often.
Function syntax is fairly simple. There are basically four parts (Figure 5-21 ). The return type, the
function name, the argument list (inside the parentheses), and the code that does the work between
the curly brackets.
Figure 5-21. The Start function on lines 15-17
In the Start function, the first word is void . It is a reserved word (you may not use it as a variable or
function name), and it tells you if a function will return a value. If it is void , that means that no value
will be returned.
The next word is the name of the function. In Unity, the convention is to capitalize the first character
of function names. Just as with variable and script names, you may not use spaces but may use
CamelCase or underscores. Reserved words may not be used either—if it turns blue, add an extra
character to the name to change it slightly.
In the parentheses, you will find arguments if the function uses them, The parentheses are
mandatory, but the arguments in side them are optional. An example of use of an argument could
be a function named PaintMe . It could take an argument of type Color and would change the color
of an object (Figure 5-22 ). An argument is a variable whose scope will only be within that particular
function.
Figure 5-22. A function with an argument of type Color , where the value is assigned to a local variable named newColor
 
Search WWH ::




Custom Search