Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Mastering Unity Scripting
  • Table Of Contents Toc
  • Feedback & Rating feedback
Mastering Unity Scripting

Mastering Unity Scripting

By : Alan Thorn
4.5 (14)
close
close
Mastering Unity Scripting

Mastering Unity Scripting

4.5 (14)
By: Alan Thorn

Overview of this book

Mastering Unity Scripting is an advanced book intended for students, educators, and professionals familiar with the Unity basics as well as the basics of scripting. Whether you've been using Unity for a short time or are an experienced user, this book has something important and valuable to offer to help you improve your game development workflow.
Table of Contents (12 chapters)
close
close
11
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/.

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Mastering Unity Scripting
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon