Programming Chapter 4

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
m (Text replace - "</csharp>" to "</syntaxhighlight>")
 
(3 intermediate revisions by 3 users not shown)
Line 5: Line 5:
 
Enumerations are custom data types with a predefined set of values. Lets create a new file and call it "Weather" and add an enumeration with the name Temperatures like this:
 
Enumerations are custom data types with a predefined set of values. Lets create a new file and call it "Weather" and add an enumeration with the name Temperatures like this:
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
using UnityEngine;
 
using UnityEngine;
 
using System.Collections;
 
using System.Collections;
Line 11: Line 11:
 
public class Weather : MonoBehaviour
 
public class Weather : MonoBehaviour
 
{
 
{
public enum Temperatures
+
    public enum Temperatures
{
+
    {
    Unknown,
+
        Unknown,
    Freezing,
+
        Freezing,
    Cold,
+
        Cold,
    Mild,
+
        Mild,
    Warm,
+
        Warm,
    Hot
+
        Hot
}
+
    }
+
   
public Temperatures temperature = Temperatures.Unknown;
+
    public Temperatures temperature = Temperatures.Unknown;
+
   
protected void Update()
+
    protected void Update()
{
+
    {
}
+
    }
+
   
 
     protected void OnGUI()
 
     protected void OnGUI()
 
     {
 
     {
 
     }
 
     }
 
}
 
}
</csharp>
+
</syntaxhighlight>
  
 
Here we've created a type called Temperatures and created a variable setting it's initial value to Unknown from the Temperatures type. The value of our variable can only be one of the Temperatures. Now create an empty game object and attach this weather script to it. Go to the inspector and... we get a dropdown list with only these items.
 
Here we've created a type called Temperatures and created a variable setting it's initial value to Unknown from the Temperatures type. The value of our variable can only be one of the Temperatures. Now create an empty game object and attach this weather script to it. Go to the inspector and... we get a dropdown list with only these items.
Line 42: Line 42:
 
'''Import the namespaces'''
 
'''Import the namespaces'''
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
using UnityEngine;
 
using UnityEngine;
 
using System.Collections;
 
using System.Collections;
</csharp>
+
</syntaxhighlight>
  
 
Here we import the UnityEngine namespace and System.Collections namespace, which gives us:
 
Here we import the UnityEngine namespace and System.Collections namespace, which gives us:
Line 54: Line 54:
 
'''Declare class and inherit from MonoBehaviour, and an enum'''
 
'''Declare class and inherit from MonoBehaviour, and an enum'''
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
public class Weather : MonoBehaviour
 
public class Weather : MonoBehaviour
 
{
 
{
Line 70: Line 70:
 
     ...
 
     ...
 
}
 
}
</csharp>
+
</syntaxhighlight>
  
 
Our own custom weather class with a custom enumeration called Temperature. We also created a variable and set the initial value.
 
Our own custom weather class with a custom enumeration called Temperature. We also created a variable and set the initial value.
Line 77: Line 77:
 
'''Methods'''
 
'''Methods'''
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
protected void Update()
 
protected void Update()
 
{
 
{
Line 85: Line 85:
 
{
 
{
 
}
 
}
</csharp>
+
</syntaxhighlight>
  
 
We have two methods... which are actually inherited from MonoBehaviour. We'll come back to inheriting functions later. For now, go check the documentation and you should see a section with '''Overridable Functions''' which contains "Update" and "OnGUI". If you read the descriptions it says that Update is called every frame, if the MonoBehaviour is enabled. And OnGUI says it is called for rendering and handling GUI events.
 
We have two methods... which are actually inherited from MonoBehaviour. We'll come back to inheriting functions later. For now, go check the documentation and you should see a section with '''Overridable Functions''' which contains "Update" and "OnGUI". If you read the descriptions it says that Update is called every frame, if the MonoBehaviour is enabled. And OnGUI says it is called for rendering and handling GUI events.
  
OK, so lets play a little more. Add the following:
+
OK, so let's play a little more. Add the following:
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
public float temperatureDegrees = 39.0f;
 
public float temperatureDegrees = 39.0f;
  
 
protected void Update()
 
protected void Update()
 
{
 
{
temperatureDegrees++;
+
    temperatureDegrees++;
 
}
 
}
  
 
protected void OnGUI()
 
protected void OnGUI()
 
{
 
{
GUILayout.Label(temperature.ToString() + " " + temperatureDegrees.ToString() + "F");
+
    GUILayout.Label(temperature.ToString() + " " + temperatureDegrees.ToString() + "F");
 
}
 
}
</csharp>
+
</syntaxhighlight>
  
 
Run it and you should see the string "Unknown" on the screen with a fast rising temperature. Update is being called every frame so every second our degree changes quite a bit (depending on our Frames Per Second). Now if you look at the documentation for Update, then see that it says the function is only called if the Behaviour is enabled. Clicking on Behaviour shows under the '''Variables''' section, there is one called enabled. Click it and it says it is a bool type (javascript is var name : type). So being the resourceful people that we are, lets modify our Weather.cs file and disable it after one run as follows:
 
Run it and you should see the string "Unknown" on the screen with a fast rising temperature. Update is being called every frame so every second our degree changes quite a bit (depending on our Frames Per Second). Now if you look at the documentation for Update, then see that it says the function is only called if the Behaviour is enabled. Clicking on Behaviour shows under the '''Variables''' section, there is one called enabled. Click it and it says it is a bool type (javascript is var name : type). So being the resourceful people that we are, lets modify our Weather.cs file and disable it after one run as follows:
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
protected void Update()
 
protected void Update()
 
{
 
{
temperatureDegrees++;
+
    temperatureDegrees++;
enabled = false;
+
    enabled = false;
 
}
 
}
</csharp>
+
</syntaxhighlight>
  
 
Run and... oh crickey! Note that we didn't have to declare the variable enabled, that's done in the parent class. But notice that it disables pretty much our whole script, the OnGUI doesn't run either since we disabled our Behaviour. This is useful, but not what we want for now. Seems we need more control.
 
Run and... oh crickey! Note that we didn't have to declare the variable enabled, that's done in the parent class. But notice that it disables pretty much our whole script, the OnGUI doesn't run either since we disabled our Behaviour. This is useful, but not what we want for now. Seems we need more control.
Line 121: Line 121:
 
The '''if''' statement is similar to the ternary operator as it tests a condition, but instead of returning a result it executes the next statement if it evaluates to true (so if you use a block '''{ }''' you can execute multiple statements). '''else if''' can be used to test more conditions before using an '''else''' which is a catch all to execute if all the if statements were false. Lets make a little something interactive to our Weather.cs file:
 
The '''if''' statement is similar to the ternary operator as it tests a condition, but instead of returning a result it executes the next statement if it evaluates to true (so if you use a block '''{ }''' you can execute multiple statements). '''else if''' can be used to test more conditions before using an '''else''' which is a catch all to execute if all the if statements were false. Lets make a little something interactive to our Weather.cs file:
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
protected void Update()
 
protected void Update()
 
{
 
{
if(temperatureDegrees > 100.0f)
+
    if(temperatureDegrees > 100.0f)
{
+
    {
temperature = Temperatures.Hot;
+
        temperature = Temperatures.Hot;
}
+
    }
else if(temperatureDegrees > 70.0f)
+
    else if(temperatureDegrees > 70.0f)
{
+
    {
temperature = Temperatures.Warm;
+
        temperature = Temperatures.Warm;
}
+
    }
else if(temperatureDegrees > 50.0f)
+
    else if(temperatureDegrees > 50.0f)
{
+
    {
temperature = Temperatures.Mild;
+
        temperature = Temperatures.Mild;
}
+
    }
else if(temperatureDegrees > 32.0f)
+
    else if(temperatureDegrees > 32.0f)
{
+
    {
temperature = Temperatures.Cold;
+
        temperature = Temperatures.Cold;
}
+
    }
else
+
    else
{
+
    {
temperature = Temperatures.Freezing;
+
        temperature = Temperatures.Freezing;
}
+
    }
 
}
 
}
  
 
protected void OnGUI()
 
protected void OnGUI()
 
{
 
{
GUILayout.Label(temperature.ToString() + " " + temperatureDegrees.ToString() + "F");
+
    GUILayout.Label(temperature.ToString() + " " + temperatureDegrees.ToString() + "F");
if(GUILayout.Button("Warmer"))
+
    if(GUILayout.Button("Warmer"))
{
+
    {
temperatureDegrees += 5;
+
        temperatureDegrees += 5;
}
+
    }
+
   
if(GUILayout.Button("Colder"))
+
    if(GUILayout.Button("Colder"))
{
+
    {
temperatureDegrees -= 5;
+
        temperatureDegrees -= 5;
}
+
    }
 
}
 
}
</csharp>
+
</syntaxhighlight>
  
 
"if" works in sequence. So the first if will be checked to see if it evaluates to true, and if true it goes into the block statement following the if while the rest of the statements are ignored. So in this case the first statement evaluates to false as temperatureDegrees is less than 60, so it skips to the next statement. The second statement "else if..." evaluates to false as well and so on until we get to the if with > 32.0f, which evaluates to true. So the temperature "Cold" will be put into our temperature variable. Everything after that doesn't get evaluated as we already have a true statement.
 
"if" works in sequence. So the first if will be checked to see if it evaluates to true, and if true it goes into the block statement following the if while the rest of the statements are ignored. So in this case the first statement evaluates to false as temperatureDegrees is less than 60, so it skips to the next statement. The second statement "else if..." evaluates to false as well and so on until we get to the if with > 32.0f, which evaluates to true. So the temperature "Cold" will be put into our temperature variable. Everything after that doesn't get evaluated as we already have a true statement.
Line 167: Line 167:
 
The For loop is an iteration loop that allows you to repeat a statement over and over a certain number of times. You can throw this code in at the bottom of your OnGUI method:
 
The For loop is an iteration loop that allows you to repeat a statement over and over a certain number of times. You can throw this code in at the bottom of your OnGUI method:
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
int sum = 0;
 
int sum = 0;
  
Line 176: Line 176:
  
 
GUILayout.Label(sum.ToString());
 
GUILayout.Label(sum.ToString());
</csharp>
+
</syntaxhighlight>
  
 
At the end of this loop the value of sum will be 45 (0+1+2+3+4+5+6+7+8+9).
 
At the end of this loop the value of sum will be 45 (0+1+2+3+4+5+6+7+8+9).
Line 187: Line 187:
 
But be careful of a never ending loop (it just keeps going, and going, and going...)
 
But be careful of a never ending loop (it just keeps going, and going, and going...)
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
int i;
 
int i;
  
Line 195: Line 195:
 
   GUILayout.Label("This is the song that never ends, it just goes on and on my friend...");
 
   GUILayout.Label("This is the song that never ends, it just goes on and on my friend...");
 
}
 
}
</csharp>
+
</syntaxhighlight>
  
 
== Jump n' ==
 
== Jump n' ==
Line 205: Line 205:
 
Now lets replace our previous loop we created with this one:
 
Now lets replace our previous loop we created with this one:
  
<csharp>
+
<syntaxhighlight lang="csharp">
 
int sum = 0;
 
int sum = 0;
 
int i;
 
int i;
Line 220: Line 220:
  
 
GUILayout.Label(sum.ToString());
 
GUILayout.Label(sum.ToString());
</csharp>
+
</syntaxhighlight>
  
 
In this example sum will be 40 (0+1+2+3+4+6+7+8+9) since we skipped 5 and quit when i got to 10.
 
In this example sum will be 40 (0+1+2+3+4+6+7+8+9) since we skipped 5 and quit when i got to 10.

Latest revision as of 20:45, 10 January 2012

Contents

[edit] Enum-ination

Lets start out by creating a new scene, "Example-4", along with a new asset folder, "Example-4 Assets", move the scene into the folder, repeat, lather, rinse. OK, onto enumerations.

Enumerations are custom data types with a predefined set of values. Lets create a new file and call it "Weather" and add an enumeration with the name Temperatures like this:

using UnityEngine;
using System.Collections;
 
public class Weather : MonoBehaviour
{
    public enum Temperatures
    {
        Unknown,
        Freezing,
        Cold,
        Mild,
        Warm,
        Hot
    }
 
    public Temperatures temperature = Temperatures.Unknown;
 
    protected void Update()
    {
    }
 
    protected void OnGUI()
    {
    }
}

Here we've created a type called Temperatures and created a variable setting it's initial value to Unknown from the Temperatures type. The value of our variable can only be one of the Temperatures. Now create an empty game object and attach this weather script to it. Go to the inspector and... we get a dropdown list with only these items.

[edit] Help Me Doc

Now we're going to modify the previous example slowly but surely throughout the chapter, but first lets get a little more knowledgeable about Unity and our custom script. Lets break it apart in small steps:


Import the namespaces

using UnityEngine;
using System.Collections;

Here we import the UnityEngine namespace and System.Collections namespace, which gives us:


Declare class and inherit from MonoBehaviour, and an enum

public class Weather : MonoBehaviour
{
    public enum Temperatures
    {
        Unknown,
        Freezing,
        Cold,
        Mild,
        Warm,
        Hot
    }
 
    public Temperatures temperature = Temperatures.Unknown;
    ...
}

Our own custom weather class with a custom enumeration called Temperature. We also created a variable and set the initial value.


Methods

protected void Update()
{
}
 
protected void OnGUI()
{
}

We have two methods... which are actually inherited from MonoBehaviour. We'll come back to inheriting functions later. For now, go check the documentation and you should see a section with Overridable Functions which contains "Update" and "OnGUI". If you read the descriptions it says that Update is called every frame, if the MonoBehaviour is enabled. And OnGUI says it is called for rendering and handling GUI events.

OK, so let's play a little more. Add the following:

public float temperatureDegrees = 39.0f;
 
protected void Update()
{
    temperatureDegrees++;
}
 
protected void OnGUI()
{
    GUILayout.Label(temperature.ToString() + " " + temperatureDegrees.ToString() + "F");
}

Run it and you should see the string "Unknown" on the screen with a fast rising temperature. Update is being called every frame so every second our degree changes quite a bit (depending on our Frames Per Second). Now if you look at the documentation for Update, then see that it says the function is only called if the Behaviour is enabled. Clicking on Behaviour shows under the Variables section, there is one called enabled. Click it and it says it is a bool type (javascript is var name : type). So being the resourceful people that we are, lets modify our Weather.cs file and disable it after one run as follows:

protected void Update()
{
    temperatureDegrees++;
    enabled = false;
}

Run and... oh crickey! Note that we didn't have to declare the variable enabled, that's done in the parent class. But notice that it disables pretty much our whole script, the OnGUI doesn't run either since we disabled our Behaviour. This is useful, but not what we want for now. Seems we need more control.

[edit] Select Your Path

The if statement is similar to the ternary operator as it tests a condition, but instead of returning a result it executes the next statement if it evaluates to true (so if you use a block { } you can execute multiple statements). else if can be used to test more conditions before using an else which is a catch all to execute if all the if statements were false. Lets make a little something interactive to our Weather.cs file:

protected void Update()
{
    if(temperatureDegrees > 100.0f)
    {
        temperature = Temperatures.Hot;
    }
    else if(temperatureDegrees > 70.0f)
    {
        temperature = Temperatures.Warm;
    }
    else if(temperatureDegrees > 50.0f)
    {
        temperature = Temperatures.Mild;
    }
    else if(temperatureDegrees > 32.0f)
    {
        temperature = Temperatures.Cold;
    }
    else
    {
        temperature = Temperatures.Freezing;
    }
}
 
protected void OnGUI()
{
    GUILayout.Label(temperature.ToString() + " " + temperatureDegrees.ToString() + "F");
    if(GUILayout.Button("Warmer"))
    {
        temperatureDegrees += 5;
    }
 
    if(GUILayout.Button("Colder"))
    {
        temperatureDegrees -= 5;
    }
}

"if" works in sequence. So the first if will be checked to see if it evaluates to true, and if true it goes into the block statement following the if while the rest of the statements are ignored. So in this case the first statement evaluates to false as temperatureDegrees is less than 60, so it skips to the next statement. The second statement "else if..." evaluates to false as well and so on until we get to the if with > 32.0f, which evaluates to true. So the temperature "Cold" will be put into our temperature variable. Everything after that doesn't get evaluated as we already have a true statement.

[edit] Iterate Iterate Iterate...

The For loop is an iteration loop that allows you to repeat a statement over and over a certain number of times. You can throw this code in at the bottom of your OnGUI method:

int sum = 0;
 
for(int i=0; i<10; i++)
{
   sum += i;
}
 
GUILayout.Label(sum.ToString());

At the end of this loop the value of sum will be 45 (0+1+2+3+4+5+6+7+8+9).

There are three statements required by a for loop (reminder, statements are separated by a semi-colon):

  • The initial value, in this case it is i=0 (you can initialize variable earlier).
  • The condition to continue the loop, in this case while i<10 we continue.
  • The step the index takes, in this case increase i by 1 i++ (you can also do decrease).

But be careful of a never ending loop (it just keeps going, and going, and going...)

int i;
 
// i will always be less than 10 (theoretically), since we just keep decreasing it's value
for(i=0; i<10; i--)
{
   GUILayout.Label("This is the song that never ends, it just goes on and on my friend...");
}

[edit] Jump n'

There are two main jump statements:

  • continue: jump back to the control statement.
  • break: break out of the control statement.

Now lets replace our previous loop we created with this one:

int sum = 0;
int i;
for(i=0; i<20; i++)
{
   // if i is 5 then don't add to sum
   if(i>4 && i<6) continue;
 
   // if i is 9 quit this loop
   if(i>9) break;
 
   sum += i;
}
 
GUILayout.Label(sum.ToString());

In this example sum will be 40 (0+1+2+3+4+6+7+8+9) since we skipped 5 and quit when i got to 10.

[edit] Recap

  • enum is the keyword used to create an enumeration type.
    • The values for an enum are comma separated and enclosed in a block { }
  • The Update and OnGUI methods are inherited from MonoBehaviour
  • enabled is a bool value which enables or disables our script
  • The if statement executes the code in it's block if it evaluates to true, otherwise it falls to the next block which can be if else or else if one exists.
  • The for statement executes the code in it's block the specified number of times until the condition is met.

Programming Index : Previous Chapter : Next Chapter

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox