Unreal Development Kit Game Programming with UnrealScript:Beginner's Guide
上QQ阅读APP看书,第一时间看更新

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 value, for example if we wanted to count down instead of up. The second part of the statement tells the for loop when to stop. Once the condition is false the loop exits, in this case once m reaches 3. The third part of the statement runs every time a loop finishes. In this case, the ++ operator is used to increment m by 1 each time.

While

While is similar to a for loop, but there is no initializing or incrementing. While loops are dangerous; if used improperly, it could lead to an infinite loop which crashes the game.