Friday, October 21, 2011

Using Timers in UnrealScript

Timers are counters that exist in the Actor class. Each timer has a function that is called when the timer finish counting.

Let's see a very simple example of Timer that counts 3 seconds and then explodes :)
class SimpleTimer extends Actor
      placeable;

event PostBeginPlay()
{
    SetTimer(3);
}
function Timer()
{    
    //this command writes a message on the screen
    worldinfo.game.broadcast(self, "KABOOM");
}

The function SetTimer() takes as argument the amount of time in seconds. A function named Timer() is called when this time has elapsed. After that the timer is deactivated.

The function SetTimer() has some optional parameters as shown below:

function SetTimer(float inRate, optional bool inbLoop, optional Name inTimerFunc='Timer', optional Object inObj)

Parameters description:
  • inRate: Execution time in seconds;
  • inbLoop: Boolean variable (true or false) that defines if the Timer should be repeated;
  • inTimerFunc: Name of the function that will be called when the timer finish;
  • inObj: Name of the object that contains the function to be called;

    In the next example we will make a timer that create an enemy on the level every 10 seconds. When four enemies has been created the timer will be deactivated.
    class TestTimer extends Actor
          placeable;
    
    var int numEnemies;    
        
    event PostBeginPlay()
    {
        SetTimer(10, true, 'createEnemy');    
        numEnemies= 0;    
    }
    function createEnemy()
    {
        local Pawn enemy;
        enemy = spawn(class 'UTGame.UTPawn'); 
        enemy.SpawnDefaultController();
        
        numEnemies++;    
        if( numEnemies >= 4 )
        {
            ClearTimer('createEnemy');        
        }    
    }
    

    To test this code just put in the level an instance of TestTimer. The enemies will be created in the same location of this TestTimer.

    There are other functions related to Timers:
    • function ClearTimer(optional Name inTimerFunc='Timer', optional Object inObj): Deactivates the Timer.

    • function ClearAllTimers(optional Object inObj): Deactivates all the Timers.

    • function PauseTimer( bool bPause, optional Name inTimerFunc='Timer', optional Object inObj ): Pause/Unpause the Timer.

    • function bool IsTimerActive(optional Name inTimerFunc='Timer', optional Object inObj): Checks if the Timer is running.

    • function float GetTimerCount(optional Name inTimerFunc='Timer', optional Object inObj): Returns the time elapsed.

    • function float GetTimerRate(optional name TimerFuncName = 'Timer', optional Object inObj): Returns the execution time.

    • function float GetRemainingTimeForTimer(optional name TimerFuncName = 'Timer', optional Object inObj): Returns the remaining time.