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)
Line 1: Line 1:
 
Author: Lucas Goss
 
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.
 +
 +
====JScript - Function ====
 +
<javascript>
 +
// function FunctionName(parameters) : type
 +
 +
// This function takes as input two numbers and adds them, returning the value
 +
function Add(number1 : int, number2 : int) : int
 +
{
 +
    return number1 + number2;
 +
}
 +
 +
// This function has no parameters and returns nothing
 +
function Start()
 +
{
 +
    // Call a function using it's name and parameter list
 +
    var sum = Add(3, 4);
 +
}
 +
</javascript>
 +
 +
====C# - Function ====
 +
<csharp>
 +
// 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 Start()
 +
{
 +
    // Call a function using it's name and parameter list
 +
    int sum = Add(3, 4);
 +
}
 +
</csharp>
 +
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 of Information ==
Line 153: Line 196:
 
== I Object ==
 
== I Object ==
  
'''TODO'''
+
An object (class) defines the characteristics of some thing. In .NET for example, every class is a child of the object class. The '''object''' class (another keyword) has some basic characteristics that are defined for everything. And '''class''' is the keyword to define an object in JScript and C#. Note that variables are sometimes called fields or attributes within a class, and functions may be called methods or behaviors in a class. 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...
  
== Scope Modifiers ==
+
====JScript - Object====
 +
<javascript>
 +
// This is an variable (field, attribute) within the HelloWorld class
 +
var message : String = "Hello World!";
 +
 +
// This is a method within the HelloWorld class
 +
function Start()
 +
{
 +
// Debug is a Debug object that uses the . operator to access the static method "Log",
 +
// which takes one parameter of type string. A static method is one that can be accessed
 +
// without using the keyword new
 +
Debug.Log(message);
  
'''TODO '''
+
// Declare an int variable and set the value to 5
 +
var x = 5;
  
== Are we Functional? ==
+
// ToString is a method of x... it is a member of the object class that gets the string
 +
// representation of an object. In this case "5" the string, not the number
 +
Debug.Log(x.ToString());
  
'''TODO'''
+
// Almost everything is an object (or appears to be)...
 +
Debug.Log(21.ToString());
 +
Debug.Log("Done".ToString());
 +
}
 +
 +
 +
// Another method
 +
function Update()
 +
{
 +
// guiText is a GUIText object that uses the . operator to access the member variable "text"
 +
guiText.text = message;
 +
}
 +
</javascript>
 +
 
 +
====C# - Object====
 +
<csharp>
 +
using UnityEngine;
 +
using System.Collections;
 +
 +
// This is a HelloWorld class, that is public and a child of (inherits) MonoBehavior
 +
public class HelloWorld : MonoBehaviour
 +
{
 +
// This is an variable (field, attribute) within the HelloWorld class
 +
public string message = "Hello World!";
 +
 +
// This is a method within the HelloWorld class
 +
void Start ()
 +
{
 +
// Debug is a Debug object that uses the . operator to access the static method "Log",
 +
// which takes one parameter of type string. A static method is one that can be accessed
 +
// without using the keyword new
 +
Debug.Log(message);
 +
 
 +
// Declare an int variable and set the value to 5
 +
int x = 5;
 +
 
 +
// ToString is a method of x... it is a member of the object class that gets the string
 +
// representation of an object. In this case "5" the string, not the number
 +
Debug.Log(x.ToString());
 +
 
 +
// Almost everything is an object (or appears to be)...
 +
Debug.Log(21.ToString());
 +
Debug.Log("Done".ToString());
 +
}
 +
 +
// Another method
 +
void Update ()
 +
{
 +
// guiText is a GUIText object that uses the . operator to access the member variable "text"
 +
guiText.text = message;
 +
}
 +
}
 +
</csharp>
 +
In C# we had to declare class, JScript automatically creates a class if it's not defined (you can use the keyword class in JScript as well). The HelloWorld class inherits from MonoBehavior, meaning it now has all the variables and methods that are in [http://unity3d.com/Documentation/ScriptReference/MonoBehaviour.html MonoBehavior]. 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 [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming here], but for now we'll just cover one more thing.
 +
 
 +
== Scope Modifiers ==
 +
 
 +
One last thing before we finish up. 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...
 +
====JScript - Scope Modifier====
 +
<javascript>
 +
private var message : String;
 +
</javascript>
 +
====C# - Scope Modifier====
 +
<csharp>
 +
private string message;
 +
</csharp>
 +
Now look in the inspector... message is gone! '''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. So for example, our HelloWorld class inherits from MonoBehavior. Any private variable or method in MonoBehavior cannot be used by our class, but our class can use protected and public variables and methods. The "Log" method in the "Debug" object must be a public method, because if it was private or protected we couldn't use it as it is not declared in our class and our class does not inherit from it.
  
 
== 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 193: Line 317:
 
**Concatenation: '''+''', for strings
 
**Concatenation: '''+''', for strings
 
**Member Access: '''.'''
 
**Member Access: '''.'''
 +
**An Object is defined by the keyword '''class''' and contains methods, variables, and other defining characteristics
 +
**Almost everything is of type '''object''' (and can be cast to an object)
 +
**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
  
 
== Example-2 ==
 
== Example-2 ==

Revision as of 21:21, 15 June 2007

Author: Lucas Goss

Contents

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.

JScript - Function

<javascript> // function FunctionName(parameters) : type

// This function takes as input two numbers and adds them, returning the value function Add(number1 : int, number2 : int) : int {

   return number1 + number2;

}

// This function has no parameters and returns nothing function Start() {

   // Call a function using it's name and parameter list
   var sum = Add(3, 4);

} </javascript>

C# - Function

<csharp> // 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 Start() {

   // Call a function using it's name and parameter list
   int sum = Add(3, 4);

} </csharp> 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.

JScript - Array

<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

var weapon1 = weapons[0]; // weapon1 will be "" not "Sword" because of new list weapons[5] = "Gun"; // OK now, since the size is 6 </javascript>

C# - Array

<csharp> string[] weapons = 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

string weapon1 = weapons[0]; // weapon1 will be "" not "Sword" because of new list 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

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

JavaScript Variables

<javascript> var playerName; var playerLives; var playerStrength; var isPlayerAlive; var weapons = new String[5]; var message = "Hello World!"; </javascript>

C# Variables

<csharp> string playerName; int playerLives; float playerStrength; bool isPlayerAlive; string[] weapons = new string[5]; string message = "Hello World!"; </csharp> 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

<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

<javascript> playerLives = new int(); // playerLives = 0; </javascript> The 'new' operator creates objects and invokes constructors. What? We'll explain this later.

Code - Cast Operator

<javascript> playerStrength = 2.51; // use "2.51f" in C# playerLives = (int)playerStrength; // don't need to cast in JScript </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).

Code - Arithmetic Operators

<javascript> playerLives = 3 + 2; // addition playerLives = 3 - 2; // subtraction playerLives = 3 * 2; // multiplication playerLives = 3 / 2; // division playerLives = 3 % 2; // modulus (division remainder) </javascript> 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> playerLives = 3 * (3 + 2 - (1 + 1)); </javascript> 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

<javascript> playerLives += 1; // Same as "playerLives = playerLives + 1;" playerLives -= 1; // Same as "playerLives = playerLives - 1;" </javascript> 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

<javascript> playerLives++; // player got an extra life playerLives--; // oh, but now he lost a life </javascript> The '++' and '--' are increment and decrement operators, that increment and decrement a variable by 1.

Code - Logical Operators

<javascript> 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 </javascript> 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

<javascript> // Different ways to say player is still alive if they have lives left isPlayerAlive = playerLives > 0; isPlayerAlive = playerLives >= 1; isPlayerAlive = playerLives != 0; isPlayerAlive = !(playerLives == 0); </javascript> 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

<javascript> // If player is alive, name will be LivingMan, otherwise DeadMan playerName = isPlayerAlive ? "LivingMan" : "DeadMan"; </javascript> 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

<javascript> playerName = "Super" + "Player"; // = SuperPlayer playerName += "One"; // = SuperPlayerOne </javascript> The '+' and '+=' operators are also used as shorthand for concatenation of strings.

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

An object (class) defines the characteristics of some thing. In .NET for example, every class is a child of the object class. The object class (another keyword) has some basic characteristics that are defined for everything. And class is the keyword to define an object in JScript and C#. Note that variables are sometimes called fields or attributes within a class, and functions may be called methods or behaviors in a class. 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...

JScript - Object

<javascript> // This is an variable (field, attribute) within the HelloWorld class var message : String = "Hello World!";

// This is a method within the HelloWorld class function Start() { // Debug is a Debug object that uses the . operator to access the static method "Log", // which takes one parameter of type string. A static method is one that can be accessed // without using the keyword new Debug.Log(message);

// Declare an int variable and set the value to 5 var x = 5;

// ToString is a method of x... it is a member of the object class that gets the string // representation of an object. In this case "5" the string, not the number Debug.Log(x.ToString());

// Almost everything is an object (or appears to be)... Debug.Log(21.ToString()); Debug.Log("Done".ToString()); }


// Another method function Update() { // guiText is a GUIText object that uses the . operator to access the member variable "text" guiText.text = message; } </javascript>

C# - Object

<csharp> using UnityEngine; using System.Collections;

// This is a HelloWorld class, that is public and a child of (inherits) MonoBehavior public class HelloWorld : MonoBehaviour { // This is an variable (field, attribute) within the HelloWorld class public string message = "Hello World!";

// This is a method within the HelloWorld class void Start () { // Debug is a Debug object that uses the . operator to access the static method "Log", // which takes one parameter of type string. A static method is one that can be accessed // without using the keyword new Debug.Log(message);

// Declare an int variable and set the value to 5 int x = 5;

// ToString is a method of x... it is a member of the object class that gets the string // representation of an object. In this case "5" the string, not the number Debug.Log(x.ToString());

// Almost everything is an object (or appears to be)... Debug.Log(21.ToString()); Debug.Log("Done".ToString()); }

// Another method void Update () { // guiText is a GUIText object that uses the . operator to access the member variable "text" guiText.text = message; } } </csharp> In C# we had to declare class, JScript automatically creates a class if it's not defined (you can use the keyword class in JScript as well). The HelloWorld class inherits from MonoBehavior, meaning it now has all the variables and methods that are in MonoBehavior. 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, but for now we'll just cover one more thing.

Scope Modifiers

One last thing before we finish up. 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...

JScript - Scope Modifier

<javascript> private var message : String; </javascript>

C# - Scope Modifier

<csharp> private string message; </csharp> Now look in the inspector... message is gone! 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. So for example, our HelloWorld class inherits from MonoBehavior. Any private variable or method in MonoBehavior cannot be used by our class, but our class can use protected and public variables and methods. The "Log" method in the "Debug" object must be a public method, because if it was private or protected we couldn't use it as it is not declared in our class and our class does not inherit from it.

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: .
    • An Object is defined by the keyword class and contains methods, variables, and other defining characteristics
    • Almost everything is of type object (and can be cast to an object)
    • 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

Example-2

TODO


Programming Index : Previous Chapter : Next Chapter

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox