Programming Chapter 4

From Unify Community Wiki
Jump to: navigation, search

Contents

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.

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.

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.

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...");
}

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.

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