Timers in UnrealScript

class TimerExample extends Object;

var float Timer1Duration;
var float Timer2Duration;

function Init()
{
    // Timers represent a single event in the future. You
    // tell the timer how long you want to wait, and it
    // will call a function when that time has elapsed.
    // This timer will wait 2 seconds.
    Timer1Duration = 2.0;
    SetTimer(Timer1Duration, false, 'OnTimer1Fired');

    // We can also set up another timer
    Timer2Duration = 1.0;
    SetTimer(Timer2Duration, false, 'OnTimer2Fired');

    // If you just wanted to wait, you could have used
    // Sleep(). One reason a timer may be useful is
    // that you can cancel the timer before it fires.
    // Here's an example of that.
    ClearTimer('OnTimer2Fired');
    `log("Timer 2 stopped");

    // Give the Timer2 enough time to fire, if it ever
    // was going to, to show it is in fact stopped.
    Sleep(2.0);
}

function OnTimer1Fired()
{
    `log("Timer 1 fired");
}

function OnTimer2Fired()
{
    `log("Timer 2 fired");
}

defaultproperties
{
}

In UnrealScript, timers are handled differently compared to Go. Instead of using channels, UnrealScript provides built-in timer functionality through the SetTimer function.

Here’s how the example works:

  1. We define two float variables to store the durations for our timers.

  2. In the Init function (which is similar to main in Go), we set up our timers:

    • SetTimer(Timer1Duration, false, 'OnTimer1Fired') sets a timer that will call the OnTimer1Fired function after Timer1Duration seconds. The false parameter means it will only fire once.
    • We do the same for Timer2.
  3. To demonstrate cancelling a timer, we immediately call ClearTimer('OnTimer2Fired') to stop Timer2 before it fires.

  4. We use Sleep(2.0) to pause execution for 2 seconds, giving Timer2 a chance to fire if it wasn’t stopped.

  5. The OnTimer1Fired and OnTimer2Fired functions are what get called when the timers fire. They simply log a message.

To run this code, you would typically place it in a script file in your Unreal project, and it would be executed as part of the game’s logic.

Note that UnrealScript doesn’t have direct equivalents to Go’s channels or goroutines. The timer system in UnrealScript is more integrated with the game engine’s tick system.

The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire. The output would look something like this:

Timer 2 stopped
Timer 1 fired

This example demonstrates how to use timers in UnrealScript for delayed execution and how to cancel timers before they fire.