Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Unity Scripting

You're reading from   Mastering Unity Scripting Learn advanced C# tips and techniques to make professional-grade games with Unity

Arrow left icon
Product type Paperback
Published in Jan 2015
Publisher
ISBN-13 9781784390655
Length 380 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Alan Thorn Alan Thorn
Author Profile Icon Alan Thorn
Alan Thorn
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Unity C# Refresher FREE CHAPTER 2. Debugging 3. Singletons, Statics, GameObjects, and the World 4. Event-driven Programming 5. Cameras, Rendering, and Scenes 6. Working with Mono 7. Artificial Intelligence 8. Customizing the Unity Editor 9. Working with Textures, Models, and 2D 10. Source Control and Other Tips Index

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 Score is declared to keep track of a sample score value. This variable will be used later in the function UpdateScore.
  • Lines 11, 23, and 28: The class MyScriptFile has three functions (sometimes called methods or member functions). These are Start, Update, and UpdateScore. Start and Update are special functions that Unity provides, as we'll see shortly. UpdateScore is a custom function for MyScriptFile.
  • Line 28: The UpdateScore function 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 UpdateScore function is called several times during the Start function. For each call, the execution of the Start function pauses until the UpdateScore function completes. At this point, the execution resumes in the next line.
  • Line 28: UpdateScore accepts two parameters or arguments. These are an integer AmountToAdd and a Boolean PrintToConsole. Arguments act like inputs we can plug in to the function to affect how they operate. The AmountToAdd variable expresses how much should be added to the current Score variable, and PrintToConsole determines whether the Score variable 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 the Start and Update functions.
  • Lines 31–34: Here, the score is actually updated and printed to Console, if required. Notice that the PrintToConsole argument has a default value of true already 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 of false. Line 19, in contrast, omits a second value and thereby accepts the default of true.
  • Lines 28 and 37: The UpdateScore function has a return value, which is a data type specified in line 28 before the function name. Here, the value is an int. This means on exiting or completion, the function will output an integer. The integer, in this case, will be the current Score. This is actually output in line 37 using the return statement. Functions don't have to return a value, it's not essential. If no return value is needed, the return type should be void as with Start and Update.

    Tip

    More information on functions and their usage in C# can be found at http://csharp.net-tutorials.com/basics/functions/.

You have been reading a chapter from
Mastering Unity Scripting
Published in: Jan 2015
Publisher:
ISBN-13: 9781784390655
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime