Wednesday, October 3, 2012

Cookbook: UDK timers

Timers in UDK are very useful if you want to call a postponed method (e.g. in 5seconds) or call something regularly (e.g. doing some statistics update each 10 seconds).

Syntax is very simple:


   1:  //set timer: (time to trigger,
   2:  //            true - repeated/false - once only,
   3:  //            method name to call in '')
   4:  SetTimer(2.0,,'MyTimerName');
   5:   
   6:  //stops timer execution
   7:  ClearTimer('MyTimerName');

Let's take a look at a simple example. Let's say we want to have a button that resets itself after given amount of time and additionally updates HUD with time left regularly (for HUD messaging see previous tutorial Cookbook: UDK cascading HUD messages, for kismet events see previous tutorial Cookbook: Triggering events, uscript -> kismet ).


   1:  class ButtonActorTimer extends ButtonActor;
   2:   
   3:  /** time for button to stay activated (then reset) */
   4:  var(Game) float fTimeToReset;
   5:   
   6:  /** time for tick (display message) */
   7:  var(Game) float fTimeToTick;
   8:   
   9:  var float fTimeLeft;
  10:   
  11:  //========================================================================
  12:  function TimeOut()
  13:  {
  14:      //trigger event with myself as instigator
  15:      self.TriggerEventClass(class'SeqEvent_ButtonReset', self);
  16:      Reset();
  17:  }
  18:   
  19:  //========================================================================
  20:  function TimeTick()
  21:  {
  22:      fTimeLeft -= fTimeToTick; //update time
  23:      Controller.StringToHUD(fTimeLeft$"..."); //show HUD message
  24:  }
  25:   
  26:  //========================================================================
  27:  function Set()
  28:  {
  29:      SetTimer(fTimeToReset,,'TimeOut'); //set new reset timer (called once)
  30:      fTimeLeft = fTimeToReset;
  31:      SetTimer(fTimeToTick,true,'TimeTick'); //ticking message (repeatedly)
  32:  }
  33:   
  34:  //========================================================================
  35:  function Reset()
  36:  {
  37:      ClearTimer('TimeOut'); //reset timer!
  38:      ClearTimer('TimeTick');
  39:  }

Button has two independent timers, one for reset (re-enable button, and send reset event to kismet) after time is up (door closes, etc.), second timer is for HUD update and sends time left message onto HUD.

Here is some ingame screenshot:


No comments:

Post a Comment