Unity Scripting Lesson 2

  • Unity Scripting Lesson 2

    Unity Scripting Lesson 2

    Posted by FIZIX Richard on Tue 3rd July 2012 7:21pm

    It is important to walk before we try to run. In our previous tutorial we looked at the basics of scripting, namely how to create a script and perform a few simple operations in 3D space.

    Now that you know how to create a script, it's time to understand the 4 most basic principals of scripting, that is:

    - Variables
    - Functions
    - Selection
    - Iteration

    If you have programmed or scripted anything before you have probably came into contact with these 4 things and probably already know what they are and how they work. If so then this tutorial will serve as a simple guide to the definition and syntax of variables, functions, selection statements and loops (iteration) in Unity.

    For those who haven't got a clue what these 4 things are (or only have a rough idea):

    - Variables are like storage containers, you can store information in them for later use.
    - Functions are reusable chunks of code which you can execute by calling the function name.
    - Selection statements (such as IF, ELSE IF, ELSE) allow you to select from a number of conditions.
    - Iteration is another word for LOOPS, where you can continue repeating through the same block of code until certain conditions are met.

    We will be covering each of these 4 topics in this tutorial. If you are ready, click here to continue to part 2 where we will be looking at Variables.

    First we need to create a new script, so click "Create -> JavaScript" in the project panel to create a new script and call it "FirstScript". The double click it to open it in the editor. When the script is open, delete the Update() { } function; so that you have a blank script.


    Variables are storage spaces, where you can store all kinds of information such as numbers and words. Before you can store anything in a variable you have to declare that it exists, which is done like so:



    You can call a variable just about anything, the #1 rule you should remember is that variables cannot contains spaces or special characters such as @, #, ' etc.

    You also need to tell Unity what type of variable it is. The type simply tells Unity what kind of data will be stored in the variable, of which there are a number of types such as:

    - int: Integer, contains whole numbers i.e. 5
    - float: Float, contains numbers with decimals i.e. 5.2
    - String: String, contains words so can contain almost any character
    - boolean: A true of false flag (values: "false" or "true")

    Below are some examples of variable declarations:


    var level : int = 1; var distance : float = 50.25; var message : String = "Welcome to our Unity Scripting Lesson"; var moving : boolean = false;

    In our first example we declared an integer number, which can be used to store whole numbers such as the characters level or how many gold pieces the player has collected. In the second example we created a float variable which contains a number with a decimal point, which could be used for storing things such as the distance between two objects.

    In the third example we declared a string which contained some text, notice how the text is encapsulated in quotation marks, this is very important for string variables.
    Lastly we created a boolean variable which contains a true or false flag, which can be used for on/off and true/false type data, such as whether the player character is moving or not.

    Public and Private Variables
    If you are familiar with Object Orientated Programming you will be familiar with public and private variables. In Unity you can make variables either public or private though they work differently to how you might expect in Unity. Essentially as any programmer would expect, a private variable cannot be directly accessed outside of the class that it is defined in, a public variable however can. This translates differently in Unity, so we shall explain.

    In Unity terms, if you create a script with a variable like so:


    var level : int = 1;

    That variable will be available in the inspector and thus to other scripts and can be modified outside of the script.

    If you however make it private like so:


    private var level : int = 1;

    The variable is now private and will not be seen in the inspector and therefore can only be modified by the script it was defined within.

    Also, when a variable is public, you can override the default value set in the script by editing the value in the Inspector.

    Lets put this into practice, in the script we opened, write:


    var lives : int = 10; private var level : int = 1; start() { }

    Save the script and then drag it from the Project panel up to the camera in the Hierarchy to include it in this scene, then click the camera and look at the inspector. You will be lives is listed in the inspector and you can edit its value. The level variable is not listed, it is private.

    You will get a warning message because the script isn't actually doing anything but you can ignore that for the purposes of what we are doing.

    That just about wraps up the basics of variables.


    Functions are reusable blocks of code that are contained within an object; they are called a functions in Unity but by OO convention are also called "methods". In this part of our Unity Scripting tutorial we will be looking at functions in Unity's version of JavaScript.

    Basic Structure
    I will start by pointing out that Unity has reserved functions, which are functions which are built into Unity itself and can be called by entering the functions name. Also there are two important functions called "start()" and "update()". These are constructors; special functions that execute automatically when the script is called upon.

    The start() function will execute once when the script is called, update() however will execute continuously every frame, which is important for realtime applications such as games.

    We will use the start() function to demonstrate the basic structure of a function:


    function start() { }

    You always preface the function with the word "function" when declaring it, you then have a { and } at the start and end, anything within these start and end braces are part of the function. Simple!

    You pretty much always have a start() or update() function in every Unity script.

    You can also create your own custom functions in the same way, by declaring it. When you want to use a function you have declared you call upon it in the script by typing its name followed by "()".

    Here is a simple example.


    function printMessage() { var message : String = "this is a message"; Debug.Log(message); } function Start() { printMessage(); }

    The first thing you did is create a function called printMessage() which prints a message to the log using the Debug.Log() reserved function. Then you called the printMessage function within the start function; which executes as soon as the script is instantiated. So script is instantiated (i.e. attached to an object that exists in the game world); the start function is automatically called which calls on the printMessage function.

    If you attach this script to the camera and run the game, you will see "This is a message" appear in the log.

    Passing Variables to Functions
    You can pass variables into functions, lets take the script above and move the message variable declaration into the Start() function and then pass message into the printMessage function:


    function printMessage(message : String) { Debug.Log(message); } function Start() { var message : String = "this is a message"; printMessage(message); }

    You first declare the variable, setting a type such as string. You can also set the default value. You then pass a variable in by defining it in the function declaration as we have in the above example and then including the variable name when calling the function (inside the brackets).

    Selection Statements

    So far in our scripting tutorial we have looked at variables and functions, now in part 4 we will be looking at selection. We use selection statements to select from multiple possible events depending upon one or more conditions being met.

    Selection statements will be used extensively within any game project, as there will always be a requirement to select between different branches based on conditions being met. Also the scope and usage of selection statements is huge; here are a few examples of how selection statements can be used:

    1. To detect if a menu button has been pressed
    2. To detect the players health and to continue if the player is alive and set the player to dead if their health reaches 0
    3. To toggle switches
    4. To get your game to perform different events depending on user action
    5. To detect whether a save file exists and whether it has loaded correctly
    6. To assist in validation (i.e. forms)

    The most common form of selection statement you will use is the IF statement, which we will look at first.

    IF Statements:
    If statements are probably the most common selection statements you can use. They are simple to code, accept single or multiple parameters and support else and else if statements for multiple selection.

    If we look at a couple of simple if statements to show you the syntax and how they are used:

    Single Parameters:


    if(Input.GetButtonDown("Jump")) { code to make your character jump }

    The statement above is an if statement in its simplest form. A single parameter has been passed to it (in this case, a user input option (being the button labelled "Jump"). If the Jump button is pressed, it will trigger this if statement to return a true value and thus execute the code in the braces.

    When you pass a single parameter into an if statement, it will check for a true/false result (i.e. if the variable has a value or if its empty, if a button is pressed or not). In the format above, its checking to see if the parameter is "true", if we wanted to check for the parameter to be false (so a null value; button not pressed or variable is empty), we use the "not" operator, like so:


    if(!Input.GetButtonDown("Jump")) { the code which should execute while the character isn't jumping. }

    The ! before the operator is telling Unity that you want to know if the passed parameter is returning a null value or is empty.

    Multiple Parameters:
    Now we will look at comparing multiple parameters. So to start, declare two variables at the top of the script (before the Start() or Update() function)


    var variable1 : int = 1; var variable2 : int = 0;

    Then create a start function:


    function start() { }

    And inside the start() function, place the following code.


    if(variable1 > variable2) { print("Var 1 is greater than var 2"); }

    The example above is comparing two variables to see if variable 1 has a value that is greater than variable 2, if so then the code inside the braces will be executed. When you compare variables you have a number of different operators:

    '>' A is Greater than B
    '<' A is Less Than B
    '==' A is equal to B
    '!=' A is not equal to B
    '>=' A is greater than or equal to B
    '<=' A is less than or equal to B

    How about if we want to compare more than two variables or values?

    Take a look at this example:


    if(variable1 > variable2 && variable1 != 0) { print("The comparison returned true"); }

    In the example above we are comparing two different conditions, that's variable1 is greater than variable 2 AND that variable1 is not equal to 0. The '&&' operator is used to compare two operators, with && both conditions must return true in order for the code within the braces to be executed.


    if(variable1 > variable2 || variable1 != 0) { print("The comparison returned true"); }

    In this example we have swapped the '&&' for '||' which means "OR", so the code will execute if variable1 is greater than variable2, but will also execute if variable1 is 0 regardless of the previous condition. You can create very complex conditions by adding more comparisons to the IF statement like this; although they will look complex, it reduces the number of statements and makes things more efficient to compare as much as possible in one statement where possible.

    Else and Else If:
    In the If statements above we were keeping things simple, doing a single condition, how about if we want to do something different if the variables have different different values, for example, if variable1 contains the number 5 we want to do one thing, if it contains 3 do another thing and do something else if any other value is in there?

    We do this using ELSE and ELSE IF statements, see the example below:


    if(variable1 == 5) { print("var1 is 5"); } else if(variable1 == 3) { print("var1 is 3"); } else { print("var1 is something else"); }

    In the example above, the first block of code will be executed if variable1 is equal to 5, the second block if its equal to 3 and the final block if the variable contains anything else. You can have as many else if statements as you like, for more complex selections.



    if(variable1 == 5) { print("var1 is 5"); } else { if(variable1 == 3) { print("var1 is 3"); } else { print("var1 is something else"); } }

    In the example above we have nested two If statements, nesting allows you to segment your if statements and perform different sub branches.

    SWITCH / CASE Statements:

    If you've ever programmed or scripted using other languages you may have came across switch/case statements. These statements allow you to take a single variable and perform multiple operations depending upon what that variable contains. Here is a simple example:


    switch(somevariable) { case "A": somefunction(); break; case "B": someotherfunction(); break; default: break; }

    The switch statement above takes a variable called "somevariable" and performs one of three events depending upon the value of the variable. If the variable contains A then the somefunction() function will be called. If the variable contains B, then the someotherfunction() function will be called, otherwise the default operation is used. The break statement after each case will stop the script at that point, so cases are useful for specific scenarios.

    That concludes our discussion on selection statements, in part 5 we will be looking at iteration (or loops as they are commonly called).

    Iteration (loops)

    So far in our scripting tutorial we have covered variables, functions and selection statements, three key lessons in scripting, the 4th important lesson is that of loops (iteration). Loops allow us to repeat blocks of code until certain conditions have been met; so lets look at the basic types of loop and how we implement them.

    Before we start, create a new script and attach it to the empty GameObject in the scene (like we have in the previous parts of the tutorial) and make sure it has a Start() function, not an Update() function. Obviously you can use loops in Update() functions in the same way as you can with Start() functions, but for the purpose of this tutorial we will be using a start() function.


    function Start() { }

    Throughout this lesson, simply put the code inside the functions braces unless told otherwise.

    WHILE Loops:
    While loops allow us to repeat a block of code until a condition is met, this is often used for reading through arrays of data (such as when you read through a file which you have loaded). Lets look at a simple while loop which will increment a counter on each cycle until the counter reaches 10.

    Before the Start() function, set the following variable:


    var count : int = 0;

    Then inside the start function, place the following code:


    while(count <= 10) { print("Counting " + count); count++; }

    Then run the game, you will see "Counting 10" printed to the screen as it will loop that fast you wont see the increment. So stop and open the console, you'll see Counting repeating from 0 to 10. The while loop executed the print statement until the count variable equaled 10.

    You may notice that we entered "count++;" as opposed to "count = count + 1;", count++ is simply shorthand for the latter.

    As you can see, while loops are pretty simple to create, just remember to ensure that the your loops can meet the stop condition or the code will loop infinitely which depending upon whats in the loop could crash the computer (i.e. if your setting stuff to memory, you could max out the users memory).

    FOR Loops@
    Another type of loop is the for loop, unlike the while loop, which we set the variables and stop condition either outside the loop or within the braces, with for loops you can set the conditions and incrementor within the loops initialization itself. These loops are especially suited to counters and other incremental type loops.

    So replace the code in the Start() function with the code below:


    for (var count = 0; count <= 10; count++) { print("Counting" + count); }

    With for loops you set more parameters in the loop initialization, these are:
    for(start_value, stop_condition, incrementor)

    The code does exactly the same thing as our while loop, except we've set count to 0, said to loop until count has a value less than or equal to 10 and to increment count by 1 every cycle.

    That's all there is to loops, at least for this introductory tutorial, as with everything its the syntax and how to structure a statement that's important, so you should now be able to implement loops into your scripts.

    And that concludes our beginners guide to Unity scripting.