Programming Chapter 2

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
m (Can't declare a variable to be a String and then assign a String array to it. Also no type is required due to type inference)
m ("you're" to "your" for possessive form in first sentence)
 
(26 intermediate revisions by 4 users not shown)
Line 1: Line 1:
Author: Lucas Goss
+
== 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===
 +
<syntaxhighlight lang="csharp">
 +
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());
 +
    }
 +
}
 +
</syntaxhighlight>
 +
 
 +
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.
 +
 
 +
<syntaxhighlight lang="csharp">
 +
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
  
== An Array of Information ==
+
string weapon1 = weapons[0];        // Get the first item in weapons
 +
int code2 = codes[1];                // Get the second item in codes
 +
</syntaxhighlight>
  
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.
+
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?
  
====JScript - Array ====
+
=== Call the Operator ===
<javascript>
+
var weapons : String[] = new String[5]; // Declare 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)
+
  
weapons = new String[6];                // Create a new array of size 6
+
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.
  
var weapon1 = weapons[0];              // weapon1 will be "" not "Sword" because of new list
+
===Index Operator===
weapons[5] = "Gun";                    // OK now, since the size is 6
+
</javascript>
+
  
====C# - Array ====
+
<syntaxhighlight lang="csharp">
<csharp>
+
string[] weapons = new string[5]; // Declare and create an array
string[] weapons = new string[5]; // Declare an array of 5 strings
+
 
weapons[0] = "Sword";            // Set item 0 to Sword
 
weapons[0] = "Sword";            // Set item 0 to Sword
weapons[3] = "Knife";             // Set item 3 to Knife
+
playerName = weapons[0];         // playerName to item 0
weapons[5] = "Gun";              // Error: invalid index (only 0-4 exists)
+
</syntaxhighlight>
  
weapons = new string[6];          // Create a new array of size 6
+
The index operator "[ ]", which you just saw earlier, is used to get a specified index in an array.
  
string weapon1 = weapons[0];      // weapon1 will be "" not "Sword" because of new list
+
===New Operator===
weapons[5] = "Gun";              // OK now, since the size is 6
+
</csharp>
+
So you probably noticed a '''new''' keyword, it's an operator just like the '''[]'''s are.
+
  
== Call the Operator ==
+
<syntaxhighlight lang="csharp">
 +
playerLives = new int(); // playerLives = 0, the default value for int
 +
</syntaxhighlight>
  
'''Note:''' The examples in this section use the following variables:
+
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.
  
====JavaScript Variables====
+
===Code Break===
<javascript>
+
<syntaxhighlight lang="csharp">
var playerName;
+
using UnityEngine;
var playerLives;
+
using System.Collections;
var playerStrength;
+
var isPlayerAlive;
+
var weapons = new String[5];
+
var message = "Hello World!";
+
</javascript>
+
  
====C# Variables====
+
public class Script1 : MonoBehaviour
<csharp>
+
{
string playerName;
+
    // This function has no parameters and returns nothing
int playerLives;
+
    void OnGUI()
float playerStrength;
+
    {
bool isPlayerAlive;
+
        string[] weapons = new string[5]; // Declare and create an array of 5 strings
string[] weapons = new string[5];
+
        weapons[0] = "Sword";             // Set item 0 to Sword
string message = "Hello World!";
+
        weapons[3] = "Knife";            // Set item 3 to Knife
</csharp>
+
        weapons[5] = "Gun";              // Error: invalid index (only 0-4 exists)
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 a few common ones.
+
  
====Code - Index Operator====
+
        GUILayout.Label(weapons[0]);
<javascript>
+
weapons[0] = "Sword";   // Set item 0 to Sword
+
playerName = weapons[0]; // playerName to item 0
+
</javascript>
+
The index operator "[]", which you just saw earlier, is used to get a specified index in an array.
+
  
====Code - New Operator====
+
        weapons = new string[6];         // Create a new array of size 6
<javascript>
+
playerLives = new int(); // playerLives = 0;
+
</javascript>
+
The 'new' operator creates objects and invokes constructors. What? We'll explain this later.
+
  
====Code - Cast Operator====
+
        string weapon1 = weapons[0];     // weapon1 will be "" not "Sword" because of new list
<javascript>
+
        weapons[5] = "Gun";               // OK now, since the size is 6
playerStrength = 2.51;             // use "2.51f" in C#
+
       
playerLives = (int)playerStrength; // don't need to cast in JScript
+
        GUILayout.Label(weapon1);
</javascript>
+
    }
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.  C# will error if you don't have an "f" on the end of 2.51, because by default all decimal numbers are double. The f suffix is a shorthand cast to a float. JScript does implicit casting, meaning it will automatically cast to whatever type the object is. C# requires more explicit casting (you have to do it yourself). There are highs and lows to both, as sometimes you can lose information in JScript and not realize it (like if a float is casted to an int and back to a float).
+
}
 +
</syntaxhighlight>
  
====Code - Arithmetic Operators====
+
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:
<javascript>
+
 
 +
<syntaxhighlight lang="csharp">weapons[4] = "Gun";</syntaxhighlight>
 +
 
 +
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===
 +
 
 +
<syntaxhighlight lang="csharp">
 +
float playerStrength = 2.51f;          // Need to use f for a float
 +
int playerLives = (int)playerStrength;  // Cast the float to an int
 +
</syntaxhighlight>
 +
 
 +
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===
 +
 
 +
<syntaxhighlight lang="csharp">
 +
int playerLives;
 
playerLives = 3 + 2;  // addition
 
playerLives = 3 + 2;  // addition
 
playerLives = 3 - 2;  // subtraction
 
playerLives = 3 - 2;  // subtraction
Line 84: Line 127:
 
playerLives = 3 / 2;  // division
 
playerLives = 3 / 2;  // division
 
playerLives = 3 % 2;  // modulus (division remainder)
 
playerLives = 3 % 2;  // modulus (division remainder)
</javascript>
+
</syntaxhighlight>
 +
 
 
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.
 
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.
====Code - Parenthesis====
+
 
<javascript>
+
<syntaxhighlight lang="csharp">
 +
int playerLives;
 
playerLives = 3 * (3 + 2 - (1 + 1));
 
playerLives = 3 * (3 + 2 - (1 + 1));
</javascript>
+
</syntaxhighlight>
 
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).
 
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).
  
====Code - Arithmetic Assignment Operators====
+
===Arithmetic Assignment Operator===
<javascript>
+
 
 +
<syntaxhighlight lang="csharp">
 +
int playerLives;
 
playerLives += 1; // Same as "playerLives = playerLives + 1;"
 
playerLives += 1; // Same as "playerLives = playerLives + 1;"
 
playerLives -= 1; // Same as "playerLives = playerLives - 1;"
 
playerLives -= 1; // Same as "playerLives = playerLives - 1;"
</javascript>
+
</syntaxhighlight>
 +
 
 
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.
 
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.
  
====Code - Increment/Decrement Operators====
+
===Increment and Decrement Operators===
<javascript>
+
 
 +
<syntaxhighlight lang="csharp">
 +
int playerLives;
 
playerLives++;  // player got an extra life
 
playerLives++;  // player got an extra life
 
playerLives--;  // oh, but now he lost a life
 
playerLives--;  // oh, but now he lost a life
</javascript>
+
</syntaxhighlight>
 +
 
 
The '++' and '--' are increment and decrement operators, that increment and decrement a variable by 1.
 
The '++' and '--' are increment and decrement operators, that increment and decrement a variable by 1.
  
====Code - Logical Operators====
+
===Logical Operators===
<javascript>
+
 
 +
<syntaxhighlight lang="csharp">
 +
bool isPlayerAlive;
 
isPlayerAlive = true && true;  // = true
 
isPlayerAlive = true && true;  // = true
 
isPlayerAlive = true && false;  // = false
 
isPlayerAlive = true && false;  // = false
Line 117: Line 170:
  
 
isPlayerAlive = !true;          // = false
 
isPlayerAlive = !true;          // = false
</javascript>
+
</syntaxhighlight>
 +
 
 
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.
 
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.
  
====Code - Relational Operators====
+
===Relational Operators===
<javascript>
+
 
 +
<syntaxhighlight lang="csharp">
 
// Different ways to say player is still alive if they have lives left
 
// Different ways to say player is still alive if they have lives left
 +
bool isPlayerAlive;
 
isPlayerAlive = playerLives > 0;
 
isPlayerAlive = playerLives > 0;
 
isPlayerAlive = playerLives >= 1;
 
isPlayerAlive = playerLives >= 1;
 
isPlayerAlive = playerLives != 0;
 
isPlayerAlive = playerLives != 0;
 
isPlayerAlive = !(playerLives == 0);
 
isPlayerAlive = !(playerLives == 0);
</javascript>
+
</syntaxhighlight>
 +
 
 
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 (>=).
 
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 (>=).
  
====Code - Ternary Operator====
+
===Ternary Operator===
<javascript>
+
 
 +
<syntaxhighlight lang="csharp">
 
// If player is alive, name will be LivingMan, otherwise DeadMan
 
// If player is alive, name will be LivingMan, otherwise DeadMan
playerName = isPlayerAlive ? "LivingMan" : "DeadMan";
+
string playerName = isPlayerAlive ? "LivingMan" : "DeadMan";
</javascript>
+
</syntaxhighlight>
 +
 
 
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".
 
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".
  
====Code - Concat Operators====
+
===Concat Operators===
<javascript>
+
 
 +
<syntaxhighlight lang="csharp">
 +
string playerName;
 
playerName = "Super" + "Player";  // = SuperPlayer
 
playerName = "Super" + "Player";  // = SuperPlayer
 
playerName += "One";              // = SuperPlayerOne
 
playerName += "One";              // = SuperPlayerOne
</javascript>
+
</syntaxhighlight>
 +
 
 
The '+' and '+=' operators are also used as shorthand for concatenation of strings.
 
The '+' and '+=' operators are also used as shorthand for concatenation of strings.
  
====Code - Member Access Operator====
+
===Member Access Operator===
<javascript>
+
Debug.Log(message);
+
guiText.text = message;
+
</javascript>
+
Remember those? If you did the chapter one example, "Example-1", they may be familiar to you. The member access operator is used to access the public members of an object.
+
  
== I Object ==
+
The member access operator is a little dot '''.'''
  
'''TODO'''
+
<syntaxhighlight lang="csharp">
 
+
string message = "Hello";
== Scope Modifiers ==
+
Debug.Log(message);
 
+
GUILayout.Label(message);
'''TODO '''
+
</syntaxhighlight>
 
+
== Are we Functional? ==
+
  
'''TODO'''
+
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 ==
 
== Recap ==
  
 
Things we learned:
 
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 '''[]'''
 
*An '''Array''' is a list of items, declared and indexed with '''[]'''
 
*Operators
 
*Operators
Line 196: Line 252:
 
== Example-2 ==
 
== Example-2 ==
  
'''TODO'''
+
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:
 +
 
 +
<syntaxhighlight lang="csharp">
 +
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);
 +
    }
 +
}
 +
</syntaxhighlight>
 +
 
 +
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|Programming Index]] : [[Programming_Chapter_1|Previous Chapter]] : Next Chapter
+
[[Programming|Programming Index]] : [[Programming_Chapter_1|Previous Chapter]] : [[Programming_Chapter_3|Next Chapter]]

Latest revision as of 20:36, 22 March 2012

Contents

[edit] 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:

[edit] 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.

[edit] Operation

[edit] 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?

[edit] 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.

[edit] 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.

[edit] 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.

[edit] 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...

[edit] 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.

[edit] 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).

[edit] 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.

[edit] 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.

[edit] 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.

[edit] 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 (>=).

[edit] 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".

[edit] Concat Operators

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

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

[edit] 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.

[edit] 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: .

[edit] 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