Programming Chapter 2

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
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.

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.

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
The index operator "[ ]", which you just saw earlier, is used to get a specified index in an array.

New Operator
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
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:

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
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
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.

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
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
The '++' and '--' are increment and decrement operators, that increment and decrement a variable by 1.

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.

Relational Operators
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
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
The '+' and '+=' operators are also used as shorthand for concatenation of strings.

Member Access Operator
The member access operator is a little dot .

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:

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