Programming Chapter 2

From Unify Community Wiki
Jump to: navigation, search

Contents

Are we Functional?

A function is a group of instructions that perform a specific task. If you completed Example-1, we had one function in our script, OnGUI. Lets create our own function and use the OnGUI to display the results:

Code Break

using UnityEngine;
using System.Collections;
 
public class Script1 : MonoBehaviour
{
    // A function is declared as:
    // modifiers type FunctionName(parameters)
 
    // This function takes as input two numbers and adds them, returning the value
    int Add(int number1, int number2)
    {
        return number1 + number2;
    }
 
    // This function has no parameters and returns nothing
    void OnGUI()
    {
        // Call a function using it's name and parameter list
        int sum = Add(3, 4);
        GUILayout.Label(sum.ToString());
    }
}

In C# you'll notice we have a void keyword before our function name "Start"... void is an empty type. So when you don't want to return anything you use void. return is another keyword, used to return a value from a function. You can have multiple return statements in one function, but the first one that gets called is used and the others will do nothing. So when a function reaches a return, it immediately returns that value. Note that it must be of the same type declared as the function return type. Also note that if you have a void function you can still use return, but it must be an empty "return;".

Parameters are a comma separated variable declaration that are your inputs to a function. Functions don't always have to have inputs (like OnGUI), but hopefully you can see the usefulness as in the examples above. When you call a function it must have the same number of parameters as the function declaration. The "+" sign is an operator, and the ".ToString()" after sum is a class method... we'll get to that in a moment, but first lets try our hand at arrays.

Operation

An Array of Information

An Array is simply a static list of variables, meaning it's a fixed size and doesn't change automatically. If you have an array of size 5, it stays at size 5 unless you create a new one. So you can't add items dynamically (that's a dynamic list). An array is declared with square brackets '[ ]' and the index is 0 based (meaning 0 is the first number, not 1). So a size of 5 would be numbers 0 to 4.

string[] weapons = new string[5];    // Declare and create an array
int[] codes = { 3, 8, 2 };           // Declare, create, and initialize array
 
weapons[0] = "Sword";                // Set first item in array to Sword
weapons[3] = "Knife";                // Set fourth item in array to Knife
 
weapons = new string[6];             // Create a new array
 
string weapon1 = weapons[0];         // Get the first item in weapons
int code2 = codes[1];                // Get the second item in codes

code2 will have the value of 8, while weapon1 will have the value of "", not "Sword" because the array was created again using the new operator. But what's an operator?

Call the Operator

An operator is a symbol used to operate on constants and variables. We already learned one operator, the assignment operator, but there are many others. I won't cover them all (use the language references), but I'll try to cover the most common ones.

Index Operator

string[] weapons = new string[5]; // Declare and create an array
weapons[0] = "Sword";             // Set item 0 to Sword
playerName = weapons[0];          // playerName to item 0

The index operator "[ ]", which you just saw earlier, is used to get a specified index in an array.

New Operator

playerLives = new int(); // playerLives = 0, the default value for int

The 'new' operator creates objects and invokes their constructors. What? We'll explain this later, for now lets take a break and see some of this action in Unity.

Code Break

using UnityEngine;
using System.Collections;
 
public class Script1 : MonoBehaviour
{
    // This function has no parameters and returns nothing
    void OnGUI()
    {
        string[] weapons = new string[5]; // Declare and create an array of 5 strings
        weapons[0] = "Sword";             // Set item 0 to Sword
        weapons[3] = "Knife";             // Set item 3 to Knife
        weapons[5] = "Gun";               // Error: invalid index (only 0-4 exists)
 
        GUILayout.Label(weapons[0]);
 
        weapons = new string[6];          // Create a new array of size 6
 
        string weapon1 = weapons[0];      // weapon1 will be "" not "Sword" because of new list
        weapons[5] = "Gun";               // OK now, since the size is 6
 
        GUILayout.Label(weapon1);
    }
}

You should know the drill, save the file. Now the comment says Error... but when you save the file there is no error, only a warning that a variable has been created but is never used. Well... run the program. You should notice an error pop up at the bottom saying index is out of range. This is because we are trying to use the index of 5, when only 0-4 exists. So go ahead and change the 5 to a 4:

weapons[4] = "Gun";

Run again and the error should disappear. You should also now get a label with "Sword" in the top left, but it's only printed out once because the second label is an empty string since we created a new list. So you probably noticed a new keyword, it's an operator just like the [ ]s are. We're getting to it...

Cast Operator

float playerStrength = 2.51f;           // Need to use f for a float
int playerLives = (int)playerStrength;  // Cast the float to an int

A cast simply converts one type of object to another. However, a conversion operator must be defined (which it is for most basic types). This is a straight conversion, so you may lose information if casting to a different type. In this case playerLives will get truncated to 2, losing the .51.

Arithmetic Operator

int playerLives;
playerLives = 3 + 2;   // addition
playerLives = 3 - 2;   // subtraction
playerLives = 3 * 2;   // multiplication
playerLives = 3 / 2;   // division
playerLives = 3 % 2;   // modulus (division remainder)

Those are the arithmetic operators (+, -, *, /, %). The arithmetic operators are operated on first because there is an order of operation, called the operator precedence. The assign operator has the lowest precedence, so it always goes last. So for example, the first thing the compiler does with the statement 'playerLives = 3 + 2', is add the 3 and 2 together, then that value is assigned to playerLives.

int playerLives;
playerLives = 3 * (3 + 2 - (1 + 1));

You can also use parenthesis to specify order. For every open parenthesis there must be a closing one as well, and they work just like they do in mathematics (the inner most parenthesis is executed first, then the next, and so on).

Arithmetic Assignment Operator

int playerLives;
playerLives += 1; // Same as "playerLives = playerLives + 1;"
playerLives -= 1; // Same as "playerLives = playerLives - 1;"

We've already covered the assignment operator, but there are arithmetic assignment operators as well (+=, -=, *=, /=, %=). They are a shorthand way to do an arithmetic operation on the current value. This code takes the current value of playerLives and in the first case adds one to it. The second case subtracts one from playerLives. The others work in a similar manner.

Increment and Decrement Operators

int playerLives;
playerLives++;  // player got an extra life
playerLives--;  // oh, but now he lost a life

The '++' and '--' are increment and decrement operators, that increment and decrement a variable by 1.

Logical Operators

bool isPlayerAlive;
isPlayerAlive = true && true;   // = true
isPlayerAlive = true && false;  // = false
isPlayerAlive = false && false; // = false
 
isPlayerAlive = true || true;   // = true
isPlayerAlive = true || false;  // = true
isPlayerAlive = false || false; // = false
 
isPlayerAlive = !true;          // = false

Conditional operators are a boolean type of operation. They're really important for conditional statements which we'll cover later. First there is the logical operators, AND (&&), OR (||) and NOT (!). The code above shows some truth tables using the logical operators.

Relational Operators

// Different ways to say player is still alive if they have lives left
bool isPlayerAlive;
isPlayerAlive = playerLives > 0;
isPlayerAlive = playerLives >= 1;
isPlayerAlive = playerLives != 0;
isPlayerAlive = !(playerLives == 0);

Another type of conditional operators are relational operators. These are EQUAL (==), NOT EQUAL (!=), LESS THAN (<), GREATER THAN(>), LESS THAN OR EQUAL (<=), and GREATER THAN OR EQUAL (>=).

Ternary Operator

// If player is alive, name will be LivingMan, otherwise DeadMan
string playerName = isPlayerAlive ? "LivingMan" : "DeadMan";

And a third type of conditional operator is the ternary operator (?). It returns the first expression if true and returns the second expression if false as in "condition ? 1st expression : 2nd expression". If the expression in the code above "isPlayerAlive" is true, then playerName will be "LivingMan".

Concat Operators

string playerName;
playerName = "Super" + "Player";  // = SuperPlayer
playerName += "One";              // = SuperPlayerOne

The '+' and '+=' operators are also used as shorthand for concatenation of strings.

Member Access Operator

The member access operator is a little dot .

string message = "Hello";
Debug.Log(message);
GUILayout.Label(message);

Remember those? If you read through Chapter 1, they may be familiar to you. The member access operator is used to access the members and methods of an object. Object? We'll get to those next chapter, for now lets recap what we've learned so far.

Recap

Things we learned:

  • Functions are a group of instructions that take parameters and return a type
  • An Array is a list of items, declared and indexed with []
  • Operators
    • Index: [index] where index is the 0 based number of an item
    • New: new creates a new object and invokes it's constructor
    • Cast: (type) where the object has a conversion operator for type
    • Arithmetic (and Arithmetic Assignment)
      • Addition: + (+=)
      • Subtraction: - (-=)
      • Multiplication: * (*=)
      • Division: / (/=)
      • Modulus: % (%=)
    • Increment: ++, increment by one
    • Decrement: --, decrement by one
    • Logical
      • And: &&
      • Or: ||
      • Not: !
    • Relational
      • Equal: ==
      • Not Equal: !=
      • Less Than: <
      • Greater Than: >
      • Less Than or Equal: <=
      • Greater Than or Equal: >=
    • Ternary: ?
    • Concatenation: +, for strings
    • Member Access: .

Example-2

Lets just reuse your current project and just create a new scene (command + N) or (File -> New).

  • Create a folder in the project view and name it Example-2 Assets
  • Create a script in the "Example-2 Assets" folder and name it Operation.
  • Attach the script to an empty game object.
  • Open Operation and insert this code:
using UnityEngine;
using System.Collections;
 
public class Operation : MonoBehaviour
{
    // This function has no parameters and returns nothing
    void OnGUI()
    {
        float playerStrength = 10.5f;
        int playerLives = 3;
        string playerName = "Player";
        bool isPlayerAlive = true;
 
        // Player got a 1-Up
        playerLives++;
        GUILayout.Label("Lives: " + playerLives.ToString());
 
        // Player got a special bonus and is now Super Player
        playerName = "Super " + playerName;
        GUILayout.Label(playerName);
 
        // Player got hit by a trash can
        playerStrength--;
        GUILayout.Label("Str: " + playerStrength.ToString());
 
        // Is the player still alive?
        isPlayerAlive = playerStrength > 0.0f;
        playerName += isPlayerAlive ? " Alive" : " Dead";
        GUILayout.Label(playerName);
 
        // Player gets hit by 2 meteors
        // Since we're using an int and float in the operation, the compiler
        // will automatically cast the 2 to a float as an operation requires
        // 2 of the same type to work
        playerStrength -= 2 * 5000f;
        GUILayout.Label("Str: " + playerStrength.ToString());
 
        isPlayerAlive = playerStrength > 0.0f;
        playerLives = isPlayerAlive ? playerLives : playerLives-1;
        GUILayout.Label("Lives: " + playerLives.ToString());
 
        playerName += isPlayerAlive ? " Alive" : " Dead";
        GUILayout.Label(playerName);
    }
}

OK, now save the scene (command + S) as Example-2 and put it in your "Example-2 Assets" folder. Now run it! No Errors? Well that's good, but you'll notice there was sort of a coding error in that we didn't really display what we wanted to. The last player name is "Super Player Alive Dead", we just wanted "Super Player Dead". So as an exercise in your superb coding skills, make it so that the program displays "Super Player Dead" without cheating by just using the constant string "Super Player Dead". Go for it!


Programming Index : Previous Chapter : Next Chapter

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox