Frank Moricz


Web Portfolio and Art Gallery

Magic made with caffeine and a keyboard.

Megabite #3 - Smooth Operators

In this installment, I wanted to talk about writing code.  Though a great deal can be accomplished in unity using the standard assets and visual tools, code is where it all comes together and it will be a integral to any good project.  Instead of small examples of working code, I think the easiest way for someone new to dot-syntax languages to learn is to first be able to read the code of others.  The better able someone is to read code examples, the easier it will be to customize code to your own purpose.

Games (and programs n general for that matter) are often times reliant on conditions.

  • "If this happens, do this."
  • "While this is going on, do these things."
  • "For however many of these things there are, do something each time."

The emboldened words are important, because they will be the condidtions I will go into detail about in this post.  In addition, there are the operators that will be needed in conjunction with these terms.  Operators are things like AndOr, Equal-to, Greater thanNot, etc.  Each has their own shorthand to coorespond and keep you from having to write everything out each time.  While some of them may not make immediate sense, over time you will easily become familiar with how they all come together.

  • &&   - "And"
  • ||   - "Or"
  • ==   - "Equal to"
  • !   - "Not"
  • >   - "Greater Than"
  • <   - "Less than"
  • >=   - "Greater than or equal to"
  • <=   - "Less than or equal to"

Using what we've learned from the series so far, statements like this should now make a lot more sense:

if (myVariable == myTextString) {
DoThisThing();
}

Broken down, we have: "If my variable is equal to my text string, do this thing."  Easy Peasy.  For me, if statements are some of the easiest to work with, so I would suggest that you familiarize yourself with them before moving into while or for statements.  As simple as the above example is, we can be a lot more specific and and complicated to achieve more customized results.

For instance:

if ((myVariable == myTextString) && (myOtherVariable == someOtherTextString)) {
DoThisThing();
}

or:

if ((myVariable == myTextString) || (myOtherVariable == someOtherTextString)){
DoThisThing();
}

By using these "And" or "Or" operators, we can make scripts do a lot of fun stuff. Another cool thing to make note of is the ability to script within a script.  As things progress, you will find yourself doing things like this much more often:

if (myVariable == myTextString) {
     x = (x + 1);
     if (x == 47) {
          DoThisThing();
     }
}

So, while this looks complex, it's quite easy to understand when you really go step-by-step and read it for what it all says.  "If myVariable is equal to myText string, add 1 to x.  If x is now equal to 47, do this other thing."

By doing your scripts in this way, you can get things running however you like.  As with most dot-syntax languages, unity runs things from top to bottom and will end up skipping over things that are ignored because of conditional statements.  In the above example, if myVariable isn't equal to myTextString, everything there would be skipped over.  Depending on where a script like that is placed, it may just run once or maybe even many times per second, so there are lots of results you can achieve.

An ELSE statement can save you loads of time as well.  Rather than writing out:

if (thisThing == true) {
   DoThis();
}
if (thisThing != true) {
   DoThisOtherThing();
}

This is really long winded considering the fact that we have the option of simply adding an ELSE statement.  An example:

if (thisThing == true) {
    DoThis();
 } else {
    DoThisOtherThing();
 }

See how much easier?  Again, before delving into While or For statements, I would suggest lots of practice with this lesson if it's the first time you've worked with IF.  If you're already familiar with javascript or PHP, this stuff is second nature by now and you'll likely only need to know some of the small differences that would cause errors in Unity.

On the next page, we'll discuss the FOR statement.

A FOR loop is complicated - I won't lie about that.  Looking at one for the first time is daunting.  A quick example is something like this:

for (var x = 0; x < 5; x++) {
DoThisThing();
}

Before you give up, allow me to explain.  "FOR" will loop a command or set of script elements "for" as long as you like.  In the above example, there are 3 components that make this happen.  The first one, var x = 0 simply starts a variable of "x" at 0.  The second element, x < 5 , tells the loop to do this loop as long as "x" is less than 5.  Obviously unless x got bigger than 0, it would go forever.  Hence, the third element, x++.  x++ Adds 1 to x each time the script plays through.

When used correctly, these loops can work magic for you.  It saves you a ton of work in writing out a long-winded script that would otherwise do the exact same thing, and in some cases it also helps to keep your file sizes smaller in the end.  If you had to spawn 20 enemies, for example, you wouldn't want to copy and paste the entire command 20 times.

A real-world example from a game that I currently have underway is something like this:

for (var x : int = 0; x < bagType; x++) {
var amount = x+1;
GUI.Box (Rect(18, ((amount * 23) + 110), 200, 20), "" + (items[x]));
}

Since I'm an open person but not exactly open-source, this is only a portion of a script that creates a list within a GUI inventory window.  The reason I've included it here is to show some versatility and expandability through variables.  Instead of the second element being a static number (like x < 5 in the first example), I chose to use x < bagType, which corresponds to the amount of bag slots a character has available for use.

Since this "bagType" variable will change as the game progresses, the FOR loop will change with it, and it will always display the correct amount of data that corresponds to the correct amount of available or occupied inventory slots.

In making G.I.R.Type, the dynamic "world" is made of tens of thousands of blocks, and the power of FOR is used to do that.  For your convenience and confusion, I will actually show the entire code here that designs the upper half of the world.

With a good deal of practice and perhaps some trial and error, I can recommend learning this method inside and out.  It'll save you a lot of time in the long run :)

On the next page, we'll go into the WHILE loop and blow your mind :)


A WHILE loop is a less frustrating thing than FOR, but a bit dangerous with some languages if you aren't careful.  Like FOR, you are basically executing scripts "while" something is true.  It won't end until that something is not true, so you might code yourself into a corner or end up crashing something if you aren't much more deliberate.

var x = 5;
while(x == 5){
     doStuff();
}

This is all well and good, but if "x" is never changed from 5 in this example, this script will run forever and completely crash your code.  Unity will not check to make sure you didn't make a mistake.

That said, WHILE is still a very powerful command.  I covered FOR first so we can learn something quite important - x++.  This could also be i++, q++, myVariable++ or whatEver++.  Whatever you use to start a while loop, just make sure you alter that variable while the loop is running.  The easiest way to do that is simply this:

var x = 0;
while(x < 5){
     doStuff();
     x++;
}

I will say also that if the DoStuff() function changes the x variable, you could get away with that as well, but it's cleaner code for beginners to include it as you write that first loop.

For most purposes, I prefer FOR over WHILE even now.  In some cases I'll use it, but more often than not I can do the same thing with a FOR loop.  The major difference between the two is that WHILE will not require the variable to be set within the basic command, so if you use it in places such as the Update() section of a script, you can consistently check to see if your conditional statement is true.

An on-the-fly example would be something like this, which will add 10 "health" to a player for each coin spent:

function Update() {
     while (coinSpent > amountOfHeals) {
     health = (health + 10);
     amountOfHeals++;
     }
}

This may not be the very best example, but it would be functional in certain situations.  Each game is different, but ideally we would want to use custom functions in conjunction with loops for cleaner code.

I realize that this tutorial will not be the most ideal thing for absolute beginners, but hopefully a good deal of readers will find it to be a good resource as they begin to work with code more and more often.  Loops, conditionals, and operators are brilliant in application, and it's fantastic when you see something you built from scratch really take shape as a result.

Stay tuned for next week, and please leave comments if you have any questions or corrections.