Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Unreal Development Kit Game Programming with UnrealScript: Beginner's Guide
Unreal Development Kit Game Programming with UnrealScript: Beginner's Guide

Unreal Development Kit Game Programming with UnrealScript: Beginner's Guide: Create games beyond your imagination with the Unreal Development Kit

Arrow left icon
Profile Icon Rachel Cordone
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (27 Ratings)
Paperback Dec 2011 466 pages 1st Edition
eBook
S$53.98 S$59.99
Paperback
S$74.99
Subscription
Free Trial
Arrow left icon
Profile Icon Rachel Cordone
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (27 Ratings)
Paperback Dec 2011 466 pages 1st Edition
eBook
S$53.98 S$59.99
Paperback
S$74.99
Subscription
Free Trial
eBook
S$53.98 S$59.99
Paperback
S$74.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Unreal Development Kit Game Programming with UnrealScript: Beginner's Guide

Chapter 2. Storing and Manipulating Data

Variables are a Programmer's Best Friend

If someone asked if it were raining, or which bag had more apples in it, it would be a pretty simple conversation. But how do you have that same conversation with a computer? In this chapter we're going to take a look at how to use variables and flow control to get our code to react to what's going on in the game.

In this chapter we will:

  • Discuss different types of variables including booleans, structs, enums, and arrays.

  • Learn how to set default properties for variables and how to let level designers change them.

  • Use operators on variables to add, subtract, and more.

  • Learn about using flow control to do different things under different circumstances.

Let's get started by learning about the different types of variables!

Variables and arrays


There are many different types of variables. Choosing which one we want to use depends on what we want to do with it. Knowing whether it's raining or not (true/false) is different from say, knowing a character's name ("Big McLargeHuge"). Let's take a look at some of the variables we can use and what they're used for.

Booleans

Quick, is it raining? Boolean variables, or bool for short, are your basic true/false questions. They're used for everything from asking if the player is driving a vehicle, to if the game has started, to whether or not an object can collide with anything.

It's standard for boolean variables' names to start with a lower case "b". This isn't required, but it's good to follow the guidelines to keep code consistent and easily readable.

Let's take a look at how we can use booleans in our code by adding to our AwesomeActor class.

Time for action – Using booleans


The first thing we need to do is tell the game about our variable. This is called declaration. Variables need to be declared before they can be used. Our declaration tells the game what type of variable it is as well as its name.

We'll continue with our "is it raining?" scenario for this experiment. In a game we might want to use this variable to check whether we should spawn rain effects or make changes to the lights, and so on.

Variable declaration in UnrealScript happens after the class declaration line, and before any functions. Let's add a variable to AwesomeActor.uc to see if it's raining or not.

  1. Open up our AwesomeActor.uc class in ConTEXT and add this line after our class declaration:

    var bool bIsItRaining;

    The var tells the game that we're declaring a variable. After that, is the variable type, in this case bool for boolean. After that, we tell the game our variable's name, bIsItRaining . Spaces can't be used in variable names, but underscore characters...

Time for action – Using integers


Let's make an Int.

  1. Declaring an integer is similar to what we did with bools, so let's replace our bool declaration line with this:

    var int NumberOfKittens;

    We can see that we have the same var text that declares our variable, and then we tell the game that our variable is an int. Finally, we set the name of our int to NumberOfKittens.

    The name of the variable should give a hint as to the difference between ints and floats, and why we need ints to begin with instead of using floats for everything. Since we don't want to hurt any defenseless kittens we should only be using whole numbers to represent the number of them. We don't want to have half of a kitten.

  2. As with our bool variable ints have a default value, in this case zero. We can check this by changing our PostBeginPlay function:

    function PostBeginPlay()
    {
       'log("Number of kittens:" @ NumberOfKittens);
    }
    

    Now our AwesomeActor.uc class should look like this:

    class AwesomeActor extends Actor
       placeable;
    ...

Time for action – Using floats


Floats are used when we need something that doesn't have nice neat values, like how far away something is or how accurate a weapon is. They're declared the same way as our bools and ints, so let's make one now.

  1. Replace our int declaration with this:

    var float DistanceToGo;
  2. Floats have a default value of 0.0. Let's change our PostBeginPlay function to check this.

    function PostBeginPlay()
    {
       'log("Distance to go:" @ DistanceToGo);
    }
  3. Compile and test, and our log should look like this:

    [0007.61] ScriptLog: Distance to go: 0.0000
  4. We can see that unlike ints, floats will log with a decimal place. Let's see if we can change the value. Add this line to the beginning of our PostBeginPlay function:

    DistanceToGo = 0.123;
  5. Compile and test, and we should see the fraction show up in the log:

    [0007.68] ScriptLog: Distance to go: 0.123
  6. Let's see what happens when we use the same line we did for our int. Change the line to this:

    DistanceToGo = 10 / 3;
  7. Compile and test, and our log should...

Time for action – Using strings


Well, by now we know the drill, so let's declare a string!

  1. Change our float declaration to this:

    var string DeathMessage;
  2. By default, strings are empty. We can see this... or not see this, rather, by changing our PostBeginPlay function:

    function PostBeginPlay()
    {
       'log("Death message:" @ DeathMessage);
    }
  3. Compile and test to see that nothing shows up:

    [0007.74] ScriptLog: Death message:

    Well that doesn't help much. Let's change that.

  4. Add this line to our PostBeginPlay function:

    DeathMessage = "Tom Stewart killed me!";

    Now it looks like this:

    function PostBeginPlay()
    {
        DeathMessage = "Tom Stewart killed me!";
       'log("Death message:" @ DeathMessage);
    }
  5. Compile and run the code, and check the log.

    [0007.67] ScriptLog: Death message: Tom Stewart killed me!

What just happened?

There's not much to strings either, and they're not used nearly as much as other types of variables. They're mostly used for things that need to be made readable to the player like character or...

Time for action – Using enums


That's all well and good, but how do we use them? Let's set one up in our AwesomeActor class.

  1. Add the enum below our class line.

    enum EAltitude
    {
        ALT_Underground,
        ALT_Surface,
        ALT_Sky,
        ALT_Space,
    };

    The E isn't necessary, but it helps to follow standard guidelines to make things easier to read.

  2. Now we need to declare a variable as that enum type. This is similar to declaring other variables.

    var EAltitude Altitude;
  3. Now we have a variable, Altitude, that's been declared as the enum type EAltitude . Enums default to the first value in the list, so in this case it would be ALT_Underground . Let's see if we can change that in our PostBeginPlay function.

    function PostBeginPlay()
    {
        Altitude = ALT_Sky;
        'log("Altitude:" @ Altitude);
    }

    Now our class should look like this:

    class AwesomeActor extends Actor
        placeable;
    
    enum EAltitude
    {
        ALT_Underground,
        ALT_Surface,
        ALT_Sky,
        ALT_Space,
    };
    
    var EAltitude Altitude;
    
    function PostBeginPlay...

Time for action – Using arrays


  1. Change our variable declaration line to this:

    var int Baskets[4];

    This will create an array of four baskets. That's easy enough, but how do we change their values?

  2. In our PostBeginPlay function, add these lines:

    Baskets[0] = 2;
    Baskets[1] = 13;
    Baskets[2] = 4;
    Baskets[3] = 1;

    One important thing to remember about arrays is that they start at 0. Even though we have 4 elements in our array, since it starts at 0 it only goes up to 3. If we tried to add a line like this to our function:

    Baskets[4] = 7;

    We would get an error.

  3. Let's go ahead and add the line to see what happens. It will compile just fine, but when we test it in the game we will see the error in the log file:

    [0007.53] ScriptWarning: Accessed array 'AwesomeActor_0.Baskets' out of bounds (4/4)
       AwesomeActor UEDPCAwesomeMap.TheWorld:PersistentLevel.AwesomeActor_0
       Function AwesomeGame.AwesomeActor:PostBeginPlay:0046

    The out of bounds error lets us know that we tried to access an element of the array that...

Time for action – Using dynamic arrays


Dynamic arrays are declared a bit differently than static arrays. Let's declare one now.

  1. Change our variable declaration line to this:

    var array<int> Baskets;

    As we can see, with dynamic arrays we don't put a number anywhere in it; it can be whatever size we need it to be. By default they're completely empty, so if we tried to log any of its values we would get an out of bounds warning similar to our experiment with static arrays.

  2. We can, however, assign values any time we want, so let's add this line to our PostBeginPlay function:

    Baskets[3] = 9;
  3. Then log the value like this:

    'log("Baskets:" @ Baskets[3]);

    Now our function should look like this:

    function PostBeginPlay()
    {
        Baskets[3] = 9;
    
       'log("Baskets:" @ Baskets[3]);
    }
  4. Compile and test, and we can see that the value logs fine, and we didn't get any warnings.

    [0007.82] ScriptLog: Baskets: 9

    When we assign a value, the size of the array automatically changes to that value. As with before, if we tried...

Time for action – Using structs


Going back to our basket of kittens example, what if there were other things in the basket besides kittens? How would we represent them?

  1. Let's create a struct at the top of our AwesomeActor class and put a few things in it.

    struct Basket
    {
        var string BasketColor;
        var int NumberOfKittens, BallsOfString;
        var float BasketSize;
    };

    Now we have two types of items in the basket as well as some variables to describe the basket itself.

  2. Now we need a variable of that struct so we can use it:

    var Basket MyBasket;
  3. Now we can change the values in our PostBeginPlay function.

    function PostBeginPlay()
    {
        MyBasket.NumberOfKittens = 4;
        MyBasket.BasketColor = "Yellow";
        MyBasket.BasketSize = 12.0;
        MyBasket.BallsOfString = 2;}

    That seems easy enough to handle. Let's try something a bit more complex.

  4. I heard you like structs, so we'll Inception-ize it by adding a struct inside a struct.

    struct SmallBox
    {
        var int Chocolates;
        var int Cookies;
    };
  5. Now let's...

Time for action – Using vectors


Since we already know that an actor's Location is a vector, let's play around with our AwesomeActor's location.

  1. First we'll declare a vector of our own at the top of our class.

    var vector LocationOffset;
  2. Vectors have their X, Y, and Z values set to 0.0 by default. We'll give ours a new value and add that to our actor's current location in our PostBeginPlay function.

    function PostBeginPlay()
    {
        LocationOffset.Z = 64.0;
        SetLocation(Location + LocationOffset);
    }

    When used as a location, the Z float inside a vector represents the up and down axis. Making the values of Z greater means moving it up, lower or more negative means moving it down. In our example we're going to move the actor up 64 units. We use the function in the second line, SetLocation , to tell the game to move our AwesomeActor. Since we already know its current location with the Location variable, we just add our LocationOffset to move it up 64 units.

  3. There's one thing we need to do before we...

Time for action – Using rotators


Before we use rotators on our AwesomeActor, we need to add some visual clue to let us know that it's actually rotating. To do that we're going to add another bit to our default properties like the sprite, but this time it will be an arrow we'll be able to see in the editor.

  1. Below the sprite in the default properties, add this:

    Begin Object Class=ArrowComponent Name=Arrow
    End Object
    Components.Add(Arrow)
  2. We're going to log our actor's current rotation, so inside our PostBeginPlay add this:

    'log("Rotation:" @ Rotation);

    Our class should now look like this:

    class AwesomeActor extends Actor
        placeable;
    
    function PostBeginPlay()
    {
        'log("Rotation:" @ Rotation);
    }
    
    defaultproperties
    {
        Begin Object Class=SpriteComponent Name=Sprite
            Sprite=Texture2D'EditorResources.S_NavP'
        End Object
        Components.Add(Sprite)
    
       Begin Object Class=ArrowComponent Name=Arrow
       End Object
       Components.Add(Arrow)
    }
  3. Compile and take a look in the editor. Our actor now...

Variable properties


Now we know what different types of variables are available to us and how to work with them. There are a few different variable properties that we need to know about to be able to use them to their fullest, first up, default properties.

Default properties

We know how to change a variable's value in our PostBeginPlay function, and that integers for example start out at 0 by default. But is there a better way to set an initial value? We've used it before, so you may have guessed that the default properties block at the end of our class is where we do this. Let's take a look at an example.

Time for action – Using the default properties block


  1. Let's start by defining some variables in our AwesomeActor class.

    var string MyName;
    var int NumberOfKittens;
    var float DistanceToGo;
  2. In our default properties block, we can give these variables initial values. These are assigned before any of the code is run.

    Defaultproperties
    {
        MyName="Rachel"
        NumberOfKittens=3
        DistanceToGo=120.0
    }
  3. In our PostBeginPlay function, instead of changing the values we'll just log them to see the default properties in action.

    function PostBeginPlay()
    {
        'log("MyName:" @ MyName);
        'log("NumberOfKittens:" @ NumberOfKittens);
        'log("DistanceToGo:" @ DistanceToGo);
    }

    Now our class should look like this:

    class AwesomeActor extends Actor
        placeable;
    
    var string MyName;
    var int NumberOfKittens;
    var float DistanceToGo;
    
    function PostBeginPlay()
    {
        'log("MyName:" @ MyName);
        'log("NumberOfKittens:" @ NumberOfKittens);
        'log("DistanceToGo:" @ DistanceToGo);
    }
    
    defaultproperties
    {
        MyName...

Time for action – Editable variables


  1. This one's simple. To make a variable changeable in the editor, add a set of parentheses after var, like this:

    var() int MyEditableInt;
  2. Add that variable to our class, then compile and open the editor. Double-click on the AwesomeActor to open up its properties, and we'll see the variable show up.

  3. We can also put it in a specific category if we wanted to separate our variables into groups. Let's see what it would look like in the Physics tab.

    var(Physics) int MyEditableInt;
  4. Let's compile and take a look.

What just happened?

The level designers don't need to know about every variable an actor has, but some may need to be exposed this way. This is how lights have their brightness and color changed, for instance. When creating an actor class, it's best to give some thought to what a level designer might need to change and give them access to it.

Config variables

That's good for the level designer, but what about the player? Sometimes we want to let the player themselves...

Time for action – Creating config variables


  1. To let the game know that our class needs to save config variables, first we need to let it know which file to use.

    class AwesomeActor extends Actor
        placeable
        config(Game);

    This tells the game that our class' config variables will be defined in the Game ini files as opposed to Engine or Input and so on.

  2. Now, let's make a config variable.

    var config int MyConfigInt;

    Config vars can have parentheses to let level designers change them, but they can NOT be put in the default properties block. Doing so will give a compiler error. Instead, we define their default properties in the INI file we specified. Since we used Game, we would put the default in DefaultGame.ini. Let's open that up now.

  3. In DefaultGame.ini we can see a bunch of different sections, starting with a line surrounded by brackets. The inside of these brackets specifies the package and class that the section is defining defaults for, like this:

    [Package.Class]
  4. In our case our package name...

Common operators


Beyond simple arithmetic there are many ways of dealing with our variables, each with its own syntax and effects on the different variable types. Let's discuss some of the most commonly used operators and variable functions.

Standard arithmetic

Addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ) work on all of the variable types we discussed, but have different effects on them. For floats and ints they work as we'd expect, but with multiplication and division, keep in mind the truncating that happens when working with ints.

It's also possible to use floats and ints together.

Time for action – Math!


  1. As an example, take a look at this code.

    var float Float1, Float2;
    var int Int1;
    
    function PostBeginPlay()
    {
        Float2 = Int1 / Float1;
        'log("Float2:" @ Float2);
    }
    
    defaultproperties
    {
        Int1=5
        Float1=2.0
    }
  2. We can divide an int by a float or vice versa, and we get the result we expect:

    [0008.10] ScriptLog: Float2: 2.5000

    However, if we divide an int by an int and assign it to a float, what would we expect the result to be?

  3. Let's take a look at this code:

    var float Float1;
    var int Int1, Int2;
    
    function PostBeginPlay()
    {
        Float1 = Int1 / Int2;
        'log("Float1:" @ Float1);
    }
    
    defaultproperties
    {
        Int1=5
        Int2=2
    }

    With that it looks like we'd expect the same result. Let's take a look at the log:

    [0007.66] ScriptLog: Float1: 2.0000

    When dividing ints, the truncating happens before assigning the result, even if it's a float. Depending on what we're doing this may be what we want, but it's good to keep that in mind.

  4. Two other operators that can be used for simple...

Time for action – Using modulo


  1. Let's look at an example.

    var int Int1, Int2, IntResult;
    
    function PostBeginPlay()
    {
        IntResult = Int1 % Int2;
        'log("IntResult:" @ IntResult);
    }
    
    defaultproperties
    {
        Int1=28
        Int2=5
    }

    28 divided by 5 is 5 with a remainder of 3.

  2. Let's look at the log:

    [0008.12] ScriptLog: IntResult: 3

What just happened?

You may be asking yourself, when will this ever come in handy? Let's say you wanted to know how many bullets a player had in their gun, but you only had the gun's clip size and the player's total number of bullets to work with. A line of code like this would work:

CurrentBullets = TotalBullets % ClipSize;

Instead of having to do any complicated math to figure it out you would be able to use modulo to save some headaches.

Comparisons

Comparing one variable to another is one of the essential tools of any programming language, and UnrealScript is no different. Comparisons give you a boolean true or false. If we wanted to know if two variables were the same...

Time for action – Comparisons


  1. Let's take a look at two ints and the various comparison operators we can use on them.

    var int Int1, Int2;
    
    function PostBeginPlay()
    {
        'log(Int1 == Int2);
    }
    
    defaultproperties
    {
        Int1=5
        Int2=5
    }

    Setting both of them to the same value and using the equal comparison gives us True in the log:

    [0007.79] ScriptLog: True

    If the variables weren't exactly the same, we would get False.

  2. The opposite of this comparison is "Not Equal", which is denoted by an exclamation point followed by an equal sign. If we wanted to know if two variables weren't the same, we would use this.

    var int Int1, Int2;
    
    function PostBeginPlay()
    {
        'log(Int1 != Int2);
    }
    
    defaultproperties
    {
        Int1=3
        Int2=5
    }

    Since they have different values, we'll get True in the log again:

    [0007.70] ScriptLog: True

    Equal or not equal also apply to vectors and rotators. Each element in those structs is compared to each other, and it will return False if any of them are different.

  3. For greater than or...

Time for action – Using logical operators


  1. Let's put our first example in code.

    var bool bRaining;
    var float CurrentMoney, RequiredMoney;
    
    function PostBeginPlay()
    {
        'log(!bRaining && CurrentMoney > RequiredMoney);
    }
    
    defaultproperties
    {
        CurrentMoney=20.0
        RequiredMoney=15.0
    }

    Remembering that bools are false by default, let's take a look at the log:

    [0007.94] ScriptLog: True

    Even though bRaining is False, we're asking the code if it's NOT raining, which is True. You can see why naming booleans is important now. If our variable were called bNotRaining , working with logical operators would get messy pretty quickly.

  2. Let's look at our second example.

    var string Day;
    
    function PostBeginPlay()
    {
        'log(Day == "Tuesday" || Day == "Thursday");
    }
    
    defaultproperties
    {
        Day="Monday"
    }

    Since the day variable is neither of those two, we'll get False in the log:

    [0007.79] ScriptLog: False
  3. One final operator to discuss is the EXCLUSIVE OR, denoted by two carets ( ^^ ). This will return...

Time for action – Concatenation


The good news is we've been using concatenation for awhile now, in our log lines. The two operators are the at symbol (@) and the dollar sign ($). The only difference between the two is whether or not we want a space in between the strings we're joining.

  1. Let's write some code.

    var string String1, String2, AtSign, DollarSign;
    
    function PostBeginPlay()
    {
        AtSign = String1 @ String2;
        DollarSign = String1 $ String2;
        'log("At sign:" @ AtSign);
        'log("Dollar sign:" @ DollarSign);
    }
    
    defaultproperties
    {
        String1="This is"
        String2="a test."
    }

    Looking at the log shows us the minor difference between the two:

    [0007.77] ScriptLog: At sign: This is a test.
    [0007.77] ScriptLog: Dollar sign: This isa test.

    The choice between them is as simple as the space between the joined strings.

  2. The concatenation operators can also be used with equal signs to shorten the code and get rid of the need for extra variables. The @ code could also be written like this:

    var...

Flow control


We learned about comparisons and logical operators earlier. Now what do we do if we want different things to happen depending on the results of those comparisons? Flow control helps us do exactly that. Let's learn how we can specify what happens under different circumstances.

If else

If/else is the basic flow control statement. Let's look at this sentence:

If it's raining I'll take an umbrella.

Using an if statement, that sentence would be written like this:

if(bRaining)
{
    bUmbrella = true;
}

We could also add an else statement to it:

If it's raining I'll take an umbrella, otherwise I'll wear short sleeves.

That would be written like this:

if(bRaining)
{
    bUmbrella = true;
}
else
{
    bShortSleeves = true;
}

We can also use Else If for other conditions.

If it's raining I'll take an umbrella, or if it's cold I'll wear a coat, otherwise I'll wear short sleeves.

We could write that like this:

if(bRaining)
{
    bUmbrella = true;
}
else if(Temperature < ComfortableTemperature)
{
...

Time for action – Using if/else


Let's write some code to see if/else in action for ourselves.

  1. Take the following code:

    var int Int1, Int2;
    
    function PostBeginPlay()
    {
        if(Int1 > Int2)
            'log("Int1 is greater than Int2");
        else if(Int1 == Int2)
            'log("Int1 is equal to Int2");
        else
            'log("Int1 is less than Int2");
    }
    
    defaultproperties
    {
        Int1=5
        Int2=2
    }
  2. What would we expect the result to be? Let's look at the log for the answer:

    [0007.72] ScriptLog: Int1 is greater than Int2

What just happened?

We can see that the if statement is executed and not the else if or else statements. Notice that in this example we didn't use the curly brackets in our statements. If there is only one line after the if, else if, or else statements brackets aren't necessary. However, if there are two or more lines, we would need to use brackets.

For

For is a different kind of control statement called an iterator. It will execute the code we write a specific number of times until a...

Time for action – Using the for statement


  1. Let's examine the following code:

    var int m;
    
    function PostBeginPlay()
    {
        for(m = 0; m < 3; m++)
        {
            'log("Stop hitting yourself." @ m);
        }
    }

    This is a simple way of writing the following code:

    m = 0;
    'log(m);
    m = 1;
    'log(m);
    m = 2;
    'log(m);

It might not seem like it's saving much time in this simple example, but consider a case where we would want to run the loop a hundred times. Putting it in a for loop would save a lot of unnecessary code!

If we write the PostBeginPlay function above into our AwesomeActor.uc class and compile it, then take a look at the log, we can see that it executed the code inside the for loop three times:

[0007.57] ScriptLog: Stop hitting yourself. 0
[0007.57] ScriptLog: Stop hitting yourself. 1
[0007.57] ScriptLog: Stop hitting yourself. 2

What just happened?

The first part of the for statement lets us set a variable to an initial value. Most of the time it will be 0, but there may be times when we need a different...

Time for action – Something


  1. As an example of what NOT to do, let's take this code.

    var int Int1;
    
    function PostBeginPlay()
    {
        Int1 = 5;
    
        While(Int1 > 0)
        {
            Int1 = 5;
        }
    }
  2. When we run the game with this code, it will crash.

    It is EXTREMELY IMPORTANT to always make sure the "while" condition will be met to avoid infinite loop crashes.

  3. Let's take a look at the right way to use it:

    var int Int1;
    
    function PostBeginPlay()
    {
        While(Int1 < 5)
        {
            'log("Int1" @ Int1);
            Int1++;
        }
    }

    In this case, Int1 will keep incrementing until it reaches 5, and the While loop will exit.

  4. We could also use a statement called break to exit the loop:

    var int Int1;
    
    function PostBeginPlay()
    {
        While(Int1 < 5)
        {
            'log("Int1" @ Int1);
            Int1++;
            if(Int1 == 3)
                break;
        }
    }

    In this case, the loop will exit when Int1 reaches 3 instead of continuing until it hits 5.

  5. Another statement we can use is called continue. Instead of exiting the loop...

Time for action – Using switches


  1. Let's take a look at an example of a Switch statement.

    var int Int1;
    
    function PostBeginPlay()
    {
        Int1 = 2;
    
        switch(Int1)
        {
            case 1:
                'log("Int1 == 1");
            case 2:
                'log("Int1 == 2");
            case 3:
                'log("Int1 == 3");
            default:
                'log("Int1 isn't any of those!");
        }
    }
  2. Running the code, the log looks like this:

    [0007.97] ScriptLog: Int1 == 2
    [0007.97] ScriptLog: Int1 == 3
    [0007.97] ScriptLog: Int1 isn't any of those!

What just happened?

Why did the other lines log? Unlike if/else statements, switches will continue executing the next steps after the condition is met. Sometimes we'll want it to do that, but if not we can use the break statement here too.

var int Int1;

function PostBeginPlay()
{
    Int1 = 2;

    switch(Int1)
    {
        case 1:
            'log("Int1 == 1");
            break;
        case 2:
            'log("Int1 == 2");
            break;
        case 3:
      ...

Summary


We learned a lot in this chapter about the different types of variables and how to use them.

Specifically, we covered:

  • The different types of variables including ints and floats, strings, vectors, and rotators.

  • How structs and arrays are created and how to use them.

  • How to set default properties for variables and use config files.

  • Common operators used with variables.

  • The various flow control statements to do different things under different circumstances.

Now that we've learned about variables, we're ready to start learning about the class tree and the commonly used classes in a UDK project. By the end of the next chapter we will be running our own custom game!

Left arrow icon Right arrow icon

Key benefits

  • Dive into game programming with UnrealScript by creating a working example game.
  • Learn how the Unreal Development Kit is organized and how to quickly set up your own projects.
  • Recognize and fix crashes and other errors that come up during a game's development.
  • A practical beginner's guide with fresh, fun writing that keeps you engaged as you learn game programming with UnrealScript

Description

Unreal Development Kit is the free edition of Unreal Engine—the largest game engine in existence with hundreds of shipped commercial titles. The Unreal Engine is a very powerful tool for game development but with something so complex it's hard to know where to start.This book will teach you how to use the UnrealScript language to create your own games with the Unreal Development Kit by using an example game that you can create and play for yourself. It breaks down the UnrealScript language into easy to follow chapters that will quickly bring you up to speed with UnrealScript game programming.Unreal Development Kit Game Programming with UnrealScript takes you through the UnrealScript language for the Unreal Development Kit. It starts by walking through a project setup and setting up programs to write and browse code. It then takes you through using variables, functions, and custom classes to alter the game's behavior and create our own functionality. The use and creation of Kismet is also covered. Later, using replication to create and test multiplayer games is discussed. The book closes with code optimization and error handling as well as a few of the less common but useful features of UnrealScript.

Who is this book for?

This book is written for beginners to UnrealScript, whether this is your first experience with programming or you're coming into it from another language and would like to learn how UnrealScript uses concepts you're already familiar with. If you would like to make games with the Unreal Development Kit, this book is for you.

What you will learn

  • Set up a UDK project and learn how to compile and test your own code
  • Learn how to extend the UDK s code to add your own functionality
  • Create your own game types, player camera, and HUD
  • Learn how UnrealScript interacts with Kismet and create your own Kismet actions and events
  • Use networking to create and test multiplayer games
  • Optimize your code to fix errors and performance problems
  • Use DLLBind to interact with code outside of the UDK

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 15, 2011
Length: 466 pages
Edition : 1st
Language : English
ISBN-13 : 9781849691925
Vendor :
Epic Games
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 15, 2011
Length: 466 pages
Edition : 1st
Language : English
ISBN-13 : 9781849691925
Vendor :
Epic Games
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 217.97
Unreal Development Kit Game Design Cookbook
S$82.99
Unreal Development Kit Game Programming with UnrealScript: Beginner's Guide
S$74.99
Unreal Development Kit Beginner's Guide
S$59.99
Total S$ 217.97 Stars icon

Table of Contents

10 Chapters
Project Setup and Test Environments Chevron down icon Chevron up icon
Storing and Manipulating Data Chevron down icon Chevron up icon
Understanding the Class Tree Chevron down icon Chevron up icon
Making Custom Classes Chevron down icon Chevron up icon
Using Functions Chevron down icon Chevron up icon
Using States to Control Behavior Chevron down icon Chevron up icon
Working with Kismet Chevron down icon Chevron up icon
Creating Multiplayer Games Chevron down icon Chevron up icon
Debugging and Optimization Chevron down icon Chevron up icon
Odds and Ends Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(27 Ratings)
5 star 59.3%
4 star 18.5%
3 star 18.5%
2 star 0%
1 star 3.7%
Filter icon Filter
Top Reviews

Filter reviews by




Mike May 23, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As other reviewers have mentioned, I was a little hesitant to buy this book, mainly because I've had lots of trouble with UnrealScript in the past using online resources. I did not think it was possible to have a book break things down so simply and clearly. I've had the book for under a week, but I can create any script I need all thanks to this book. Definite purchase for those who struggled learning UnrealScript from other resources.
Amazon Verified review Amazon
htl Sep 21, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
So far so good. I am a newly graduated Game Artist. I deal primarily with the art of the game, ya know the 3d models, art concepts, in game cutscenes, textures etc. In other words I don't know jack about programming whatsoever. My portfolio is lacking so I figure I learn some programming and thus this book seemed like a good idea. AND IT WAS! I program my first sprite to appear in the game (somewhere in the early chapters, those pro programmers might not find it impressive but I am an artist! its my first time) Later I programmed it to appear in the editor but not in game. I had some problems but I learned. (`this is different from this'). Now I must say as an artist I must admire and respect you programmers for your versitlity, fortitude, problem solving skills and desire to push soo hard and work long hours to know how to program. It isn't easy but this book takes you each step of the way and learn, research, expirement and think more. With strong backs and long hours programming at first seems like a scary chore but later it evolves into obsession.
Amazon Verified review Amazon
L.D. Jul 18, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a topic rarely covered in-depth, and this book really takes you through the paces building your understanding step by step. By the time chapter 8 rolls around (Creating Multiplayer Games) you're in for a mind-bending lesson on the importance of pre-planning your projects. This has been a great read.
Amazon Verified review Amazon
Scott Munday Jul 03, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've been programming in web development for ten years, but I've been programming applications for nearly twenty. I have been dabbling in video game development for a while and UDK two years ago, but could never find a good book on UnrealScript. I bought the two Mastering Unreal Technology books and was refunded for my preorder of their abandoned third book on UnrealScript. I soon had to sift through forum posts or the wiki, finding gems between the fluff and the useless posts "Why would you want to do that?". I just wanted a book on programming UnrealScript and how to apply it to developing games. I picked up this book on my Kindle, and I couldn't be more happy. There are few programming books that get it right, and this one does it in every single way. Flying through the chapters is exciting, because you are developing a game while learning or, in other words, developing theory with practice. Whether you are an old or new UDK game developer, I highly recommend this book. In my opinion, it is currently the best book on the market for UnrealScript.
Amazon Verified review Amazon
Luna V Aug 06, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Was one of the best books I ever bought back in the day. No longer relevant though- Look to the new engines(UE4) or go to Unity for your first project.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.