Programming Chapter 1 Old

From Unify Community Wiki
Jump to: navigation, search

Author: Lucas Goss

Contents

Make a Statement

A statement is basically a computer instruction. Semicolons in JavaScript and C# are for ending a statement, much like when we write sentences we end with a period. And just like you can have multiple sentences on one line, you can have multiple statements. For example:

;;;

That's three empty statements and legal code! An empty statement doesn't do anything, which is why it's called empty.

A block allows multiple statements to be written where one statement is allowed, and is the same in JavaScript and C#, using begin '{' block and '}' end block. Ready for some more do nothing code:

{ ;; }

That's valid code as well. You can also have a block inside a block (this is called nesting).

{ ; { ;; } { {} } }

Notice that for each starting '{' there is an ending '}' that matches it. This is required or else you will get an error from the compiler.

Comment Inside

A comment is a piece of text in code that does nothing:

// this is a comment in Javascript and C#
; // This is a comment after an empty statement

The '//' tells the compiler to ignore whatever follows it on the same line. There are also begin/end comments:

/*
  This comment extends
  over multiple lines.
*/
 
{ /* A begin/end comment on one line } */ }

The '/*' is the start of the comment and the '*/' is the end. Everything in between is ignored by the compiler, so it will never execute any code inside of a comment. The second comment is valid even though it has two '}' on one line, because one is inside the comment and the other is not. Since the compiler ignores code in a comment it only sees one '}'.

Free to Play

Feel free to try any of these out in Unity by creating a new Javascript or C# file and entering this code inside of the 'Update' block. Our custom code starts at the line with '// Empty statements...':

JavaScript - Play

function Update () {
    // Empty statements inside a block below
    { ;; }
}

C# - Play

using UnityEngine;
using System.Collections;
 
public class Play : MonoBehaviour
{    
    void Update()
    {
        // Empty statements inside a block below
        { ;; }
    }
}

What's your Type?

A data type is a way to tell the compiler what kind of information you want to store and how it should be analyzed. The most common types used in programming are numbers, letters and boolean (true/false). On top of this there are other predefined types in languages as well as user defined types (types that we can create). JavaScript uses dynamic typing, which means that you don't always have to tell it the type, it will dynamically try to figure out what type something is. C# uses static typing, meaning that you always have to tell it what type you want your data to be. Each has it's up and downsides, and you can find out more here (check out the Dynamic typing section).

Now I'm not going to list all the keywords and types, that's done in the references already, use them. But I'll try to explain enough so that when you look at those sites they will be useful. Here are some common types in JavaScript and C# (again, look at the references for all of them):

JavaScript C# Size Range
boolean bool N/A true or false
String string N/A 0 to approximately 2 billion Unicode characters. Each character is 16 bits (two bytes).
int int 4 bytes -2,147,483,648 to 2,147,483,647
float float 4 bytes Approximate range is -1038 to 1038 with accuracy of about 7 digits. Can represent numbers as small as 10-44

OK, now what all is that saying. A boolean type can only store true or false (a 1 or 0 underneath). Why doesn't it have a size? Probably because the language designers decided to allow the implementors (JavaScript and C# are standards and can be implemented by anyone), to be able to handle the type under the hood however they want for the sake of efficiency. Since this is a concise guide, ahem, I won't go into the gritty details and you don't need to worry about it. Now the string also doesn't have a size, but the reason for that is because it can grow and shrink as needed (for efficiencies sake). A string can store any text we want (must be a Unicode Character, but again a minor detail we don't need to worry about). The last two types are numbers, one for integers (-1, 0, 1, 2, ...), and one for decimals (-1.0, 0.0, 0.2, 1.445, ...). Why not just store everything as a decimal? Again, this is for efficiencies sake. A lot of choices made by languages have to have a balance between efficiency (sometimes caused by the underlying hardware) and usability. But don't sweat it, you don't need to remember all this. Just know there are different tools for the job... or rather different types for the job.

It's all Variable

A variable is a named location to store data. And much like the definition, the data at a location can be changed. Since the information can change it's good to think a little about how you name a variable. So lets get an example program going. Say we want to store a number, like the number of lives a player has.

JavaScript - Variable naming

// Bad name
var three;
 
// Good name
var playerLives;
 
// Good name with type
var lives : int;

C# - Variable naming

// Bad name
int three;
 
// Good name
int playerLives;

When we declare a variable in both languages, it's called a declaration statement, and declaration statements require a proper ending semicolon ';'. In JavaScript you declare a variable with the keyword var, but remember JavaScript does dynamic typing so you don't have to put the type, but you can. To tell JavaScript what type something is you follow the type with a colon ':', and then put the type (int in this case). Since C# is statically typed, it doesn't need a variable keyword because you have to tell it a type.

The name 'three' can be bad in this instance because while it may be the value we want to store, this is just the name for programmers to use, not the value. And since later the value can change (thus variable), it doesn't make sense to have a name three storing a value of one when the player has lost two lives!

Now the above variables are all well and good, but what information are they storing since we didn't tell it what to store? The answer is whatever the language uses for the default. You can find the default storage for types in the language references. Now sometimes the default value isn't what we want, so we may want to initialize the value ourselves by telling the variable what to store. It's usually a good idea to initialize variables.

JavaScript - Variable initializing

// Just use the good name
var playerLives = 3;

C# - Variable initializing

// Just use the good name
int playerLives = 3;

In those examples we store the integer 3 in our variable. The '=' is an assignment operator, it assigns the value on the right to the variable on the left. A variable in most languages usually has to start with an alpha character or an underscore (there are a few other characters allowed as well that vary by language), can only contain alpha characters, numbers, or underscores, can't contain spaces, and in the case of C# and JavaScript is case sensitive (languages like BASIC are not). So a variable named 'playerLives' is different from 'PlayerLives'.

Staying Constant

A constant is a fixed value. Unlike a variable it is constant (doesn't change). The '3' used for the player lives above is a constant. A constant cannot be assigned a value, it's constant so it can't be changed. We've only looked at numbers so far, so lets look at a string.

JavaScript - String consant

var playerName = "Super Player";

C# - String consant

string playerName = "Super Player";

Here the string "Super Player" is a constant. The variable playerName (a string type), gets assigned the value of "Super Player".

What's the Scope?

Scope is the range that a variable exists in. Once a variable is declared, you can't declare it again in the same scope.

JavaScript - Same Scope

var playerLives = 3;
 
// Remember, this will never get executed since it's in a comment.
// But if you took off the comment below you'd get an error because you defined the variable twice.
// var playerLives = 2;
 
// Change the value like this
playerLives = 2;

C# - Same Scope

int playerLives = 3;
 
// Remember, this will never get executed since it's in a comment.
// But if you took off the comment below you'd get an error because you defined the variable twice.
// int playerLives = 2;
 
// Change the value like this
playerLives = 2;

Scope is defined in a block, remember those? Also remember that a block can be nested in another block. A nested block inherits all of the variables inside it's parent block, but the parent can't redefine a variable that's declared in a child. And when variables go out of scope they are no longer defined.

JavaScript - Different Scope

var playerLives = 3;
 
{
    // This is a nested block so we don't redefine the variable, we just use it
    playerLives = 2;
 
    // We can define the same name in separate blocks though
    var playerAge = 18;
}
 
{
    // Same variable name as above, but in a different scope
    var playerAge = 16;
}
 
{
    // Taking the comment off this will give an error,
    // since variables only exist in the scope they were defined
    // playerAge = 10;
}
 
// This will also error if uncommented since the variable is not in this scope (undefined)
// playerAge = 8;
 
// And this will error if uncommented because a child has already defined this variable
// var playerAge = 5;

C# - Different Scope

int playerLives = 3;
 
{
    // This is a nested block so we don't redefine the variable, we just use it
    playerLives = 2;
 
    // We can define the same name in separate blocks though
    int playerAge = 18;
}
 
{
    // Same variable name as above, but in a different scope
    int playerAge = 16;
}
 
{
    // Taking the comment off this will give an error,
    // since variables only exist in the scope they were defined
    // playerAge = 10;
}
 
// This will also error if uncommented since the variable is not in this scope (undefined)
// playerAge = 8;
 
// And this will error if uncommented because a child has already defined this variable
// int playerAge = 5;

Recap

These are the things that you should have learned:

  • An empty statement is just a semicolon ';', and does nothing.
  • A block '{ }' allows multiple statements to be written where one is allowed.
  • A comment is ignored by the compiler and never seen.
    • '//' comments everything after it on the same line.
    • '/*' and '*/' begin and end a comment.
  • A data type tells the compiler what type of information to store.
    • JavaScript uses dynamic typing, meaning data doesn't always have to declare a type.
    • C# uses static typing, meaning a data type is always required.
  • A variable is a named location to store data.
    • A variable name:
      • Starts with a alpha character or underscore (possibly others depending on the language).
      • Can only contain alpha characters, numbers, or underscores (again possibly others).
      • Can't contain spaces.
      • Is case sensitive for JavaScript and C#.
  • A declaration statement (declaring a variable) ends with a ';'
  • An assignment operator '=' assigns a value on the right to a variable on the left.
  • A constant is a fixed value.
  • A scope is the range that a variable exists in.
    • The same variable cannot be declared twice in the same scope.

Example-1

In this section we are going to put what we have learned into practice. We will try to do a small game in every example, but for this example we will just get Unity to display a message to us. The message... Hello World!!!

First create a new project in Unity, and name it Example-1 (save it wherever you want). To start off we are going to create a folder (a good habit) to put our files in. So create a folder asset named Example-1 Assets (if you don't know how to do this, read up on the Unity Manual "Creating Assets"). Next, create a script asset in this folder (JavaScript or C#), and name it HelloWorld. Then open the file and put the following code in:

JavaScript - Hello World

// Our message variable we'll initialize with "Hello World!"
var message : String = "Hello World!";
 
// Use this for initialization
function Start()
{
	Debug.Log(message);
}
 
 
// Update is called once per frame
function Update()
{
	guiText.text = message;
}


C# - Hello World

using UnityEngine;
using System.Collections;
 
public class HelloWorld : MonoBehaviour
{
	// Our message variable we'll initialize with "Hello World!"
	public string message = "Hello World!";
 
	// Use this for initialization
	void Start ()
	{
		Debug.Log(message);
	}
 
	// Update is called once per frame
	void Update ()
	{
		guiText.text = message;
	}
}

All we added was a comment or two, a variable named "message" and gave it a value of "Hello World!" Well we also added a few other minor things like Debug.Log and guiText.text, you'll see what those are for in a moment. And don't worry about how they work just yet, we'll get to that in another chapter. Now save the scene in your "Example-1 Assets" folder as "MainScene". OK, go ahead and run the example!

Hmm, nothing happened and all you see is a blue screen. This is because our script isn't attached to anything in the scene, so it's not used. Well we want it to be used, so create a GUI Text Game Object from the menu (Game Object -> Create Other -> GUI Text) and name it HelloWorldText. Now drag the HelloWorld script we created earlier on to the HelloWorldText Game Object. In the Inspector View you should see a new HelloWorld section added, having a property named "Message". Yes, that's the message variable coming from our code with a default value of "Hello World!". You can change this later, but for now try running the program again.

Congratulations! You may have noticed the Status Bar flash some text with a blue information icon. If you click the Status Bar a window will pop up showing you the debug log with a line that says "Hello World!". Hmm, didn't we have something about a debug log in our code...


Programming Index : Previous Chapter : Next Chapter

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Tools