Programming Chapter 2 Old

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 two functions in our script: Update and Start.

C# - Function
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 Start and Update), 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... 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.

C# - Array
So you probably noticed a new keyword, it's an operator just like the []s are.

Call the Operator
Note: The examples in this section use the following variables:

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

Code - New Operator
The 'new' operator creates objects and invokes constructors. What? We'll explain this later.

Code - 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. 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. JavaScript 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 JavaScript and not realize it (like if a float is casted to an int and back to a float).

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

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

Code - Member Access Operator
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 members and methods of an object.

Class.ified
A class is a custom type that allows variables and functions that are related to be grouped together and treated as one thing. Note that variables are sometimes called fields or attributes within a class, and functions may be called methods or behaviors in a class. For a class example lets look at a point. A point in 2D space is made up of an x and y coordinate and you can translate that point to another location.

C# - Class
In Unity when you create a new script, it automatically creates a new class for you. In JavaScript you can use the keyword class as I did with the C# code, but it's not necessary as Unity automatically does this for you if it's not there. Unity also makes the JavaScript class, variables and methods public by default...

Scope Modifiers
Scope modifiers are a way to tell what "scope" a variable, method, class, etc. has. An object has full access to everything inside, however non-public items cannot be used from the outside. Using the Example-1 project again, change the message type to private and save...

C# - Scope Modifier
Now look in the inspector... message is gone! This is because the inspector will only show public variables because that's all it has access to. private only allows access from inside the class. Another type protected allows access only to the class and child classes. And public allows anyone access.

I Object
An object is a class that has been instantiated. If you tried to use the Point class that we made above like:

JavaScript

C#

You'd get an error saying something like: "Use of unassigned local variable...", or "Object reference not set to an instance of an object...". This is because your class is not instantiated. A class is just a representation of an object, but not an actual object itself (meaning the computer has not allocated any memory for it). To create an object you have to use the operator new

C# - New Operator Revisited
New is followed by a class constructor. By default an empty constructor (has no parameters) is created for you (in our case Point). A constructor initializes all of the class members (x and y in our Point class), and is required to create an object. It also must be the same name as your class. We can also create our own constructor (including our own empty constructor).

C# - Constructor
Most of the time in Unity you don't need a constructor, as you'll want to set the initial values in the editor. But you can place a default value if none is supplied by initializing variables where they are created (such as our y = 5). Lets go back to our example and use the constructor we made:

JavaScript

C#

If you noticed, we also added a call to the method ToString. But there is no method ToString in our Point class you say... well, not exactly.

In .NET, every class is a child of the object class. A child basically means that it inherits all of the members and methods of the parent. You can inherit any public class you want (making it a child) by doing:

C# - Child
Now we can use these new classes and every property of their parent. So now we can do:

JavaScript

C#

The object class (which every class inherits even without explicitly declaring it in code), has some basic characteristics that are defined for everything (which is why everything is a child of it). One of them is ToString, which gets a string representation of your class. By default the value of ToString is the name of your class. Take example one and add this to the Start method:

C# - ToString
Now run the program and the debug log should now print "Point". Of course, that's not too useful. The real power of child classes is the ability to override the parent. Change your Point class by adding this method:

C# - Custom ToString
Now if you run the program the debug log should print "[2,3]". Pretty nifty huh?

Well since everything is an object, or appears to be, there's quite a few things you can do with default types. Lets take a look at our Example-1 project that we created last chapter. Be sure to read the new comments and code added to the Start method...

C# - Object
The HelloWorld class inherits from MonoBehavior, meaning it now has all the variables and methods that are in MonoBehavior as well as object. Everything inside of the begin and end blocks is part of the HelloWorld object. Also since just about everything is an object you can cast any type to an object (using the cast operator). Well you can read more about Object Oriented Programming here.

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: .
 * A class is created using the keyword class and contains methods (functions) and members (variables)
 * Scope Modifiers
 * private is only accessible to the class defining it
 * protected is only accessible to the class defining it and classes that inherit from it
 * public is accessible to everything
 * An Object is created by instantiating a class using the keyword new followed by the constructor
 * ToString is a method in the object class, which all classes are children of
 * Almost everything is of type object (and can be cast to an object)

Example-2

 * Create a new project and name it 'Example-2.
 * 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 GameManager. Open it and insert this code.

C# - GameManager
The GameManager will process all of the users selections, make a random computer selection, compare and display the results, and keep track of the game stats. Next we need to create some buttons.


 * Create a script in the "Example-2 Assets" folder and name it TextButton. Open it and insert this code.

C# - TextButton
Now we can use that script on any GUIText object to make it a button. When pressed it will call the OnSelection method of manager. Well that's all the scripting, it's now time to create the Unity objects.


 * Create a GUI Text object, name it ResultText, and set the text to "Winner"
 * Create an Empty Game Object, and name it GameManager
 * Drag the "GameManager" script onto the "GameManager" object.
 * Select the "GameManager" object and drag the "ResultText" object onto the "Result Text" variable in the "Game Manager (Script)" section.
 * Create 3 GUI Text objects and name them PaperText, RockText, and ScissorText
 * Drag the "TextButton" script on each of them
 * Set the text to "Paper", "Rock", and "Scissors" respectively and set X position of each in the Inspector as 0.6, 0.7 and 0.8 respectively
 * Set the Normal Color to Cantaloupe
 * Set the Hover Color to Honeydew
 * Set the Pressed Color to Licorice
 * Drag the "GameManager" object on to the Manager variable
 * Save the scene as MainScene in the "Example-3 Assets" folder

Run it and... let the games begin!!!

Unity Package: [[Media:Example-2 Package.unityPackage.zip]]

Programming Index : Previous Chapter : Next Chapter