Functions
We already used functions in this chapter, such as the Start and Update functions. However, now, it's time to consider them more formally and precisely. In essence, a function is a collection of statements bundled together as a single, identifiable block, which is given a collective name and can be executed on demand, each line of the function being executed in sequence. When you think about the logic of your game, there are times when you need to perform some operations repeatedly on your objects, such as, firing a weapon, jumping in the air, killing enemies, updating the score, and playing a sound. You can copy and paste your code throughout the source file, wherever you need to reuse it; this is not a good habit to cultivate. It's easier to consolidate the recyclable code into a function that can be executed by a name when you need it, as shown in the following code sample 1-8:
01 using UnityEngine;
02 using System.Collections;
03
04 public class MyScriptFile : MonoBehaviour
05 {
06 //Private variable for score
07 //Accessible only within this class
08 private int Score = 0;
09
10 // Use this for initialization
11 void Start ()
12 {
13 //Call update score
14 UpdateScore(5, false); //Add five points
15 UpdateScore (10, false); //Add ten points
16 int CurrentScore = UpdateScore (15, false); //Add fifteen points and store result
17
18 //Now double score
19 UpdateScore(CurrentScore);
20 }
21
22 // Update is called once per frame
23 void Update ()
24 {
25 }
26
27 //Update game score
28 public int UpdateScore (int AmountToAdd, bool PrintToConsole = true)
29 {
30 //Add points to score
31 Score += AmountToAdd;
32
33 //Should we print to console?
34 if(PrintToConsole){Debug.Log ("Score is: " + Score.ToString());}
35
36 //Output current score and exit function
37 return Score;
38 }
39 }The following is the breakdown of the code present for code sample 1-8:
- Line 08: A private, integer class variable
Scoreis declared to keep track of a sample score value. This variable will be used later in the functionUpdateScore. - Lines 11, 23, and 28: The class
MyScriptFilehas three functions (sometimes called methods or member functions). These areStart,Update, andUpdateScore.StartandUpdateare special functions that Unity provides, as we'll see shortly.UpdateScoreis a custom function forMyScriptFile. - Line 28: The
UpdateScorefunction represents a complete block of code between lines 29 and 38. This specific function should be invoked every time the game score must change. When called, the code block (lines 29–38) will be executed sequentially. In this way, functions offer us code recyclability. - Lines 14-19: The
UpdateScorefunction is called several times during theStartfunction. For each call, the execution of theStartfunction pauses until theUpdateScorefunction completes. At this point, the execution resumes in the next line. - Line 28:
UpdateScoreaccepts two parameters or arguments. These are an integerAmountToAddand a BooleanPrintToConsole. Arguments act like inputs we can plug in to the function to affect how they operate. TheAmountToAddvariable expresses how much should be added to the currentScorevariable, andPrintToConsoledetermines whether theScorevariable should be shown in the Console window when the function is executed. There is theoretically no limit to the number of arguments a function can have, and a function can also have no arguments at all, such as theStartandUpdatefunctions. - Lines 31–34: Here, the score is actually updated and printed to Console, if required. Notice that the
PrintToConsoleargument has a default value oftruealready assigned to the function declaration in line 28. This makes the argument optional whenever the function is called. Lines 14, 15, and 16 explicitly override the default value by passing a value offalse. Line 19, in contrast, omits a second value and thereby accepts the default oftrue. - Lines 28 and 37: The
UpdateScorefunction has a return value, which is a data type specified in line 28 before the function name. Here, the value is anint. This means on exiting or completion, the function will output an integer. The integer, in this case, will be the currentScore. This is actually output in line 37 using thereturnstatement. Functions don't have to return a value, it's not essential. If no return value is needed, the return type should bevoidas withStartandUpdate.Tip
More information on functions and their usage in C# can be found at http://csharp.net-tutorials.com/basics/functions/.