An event based Timer class similar to Flash. [C#]

Hello everyone,

When I was making a game, I ended up creating a Timer class somewhat similar to the one found in Flash. I am not sure if anything similar is available but thought I would share it anyway. The script is in C#.

Usage:

  1. You need to call the Update() method in the script every frame. You can do this easily by attaching it to an active GameObject. I have left the method as public in case you want to do it some other way.

  2. Register the event handler and the handling method.

// Example

void SomeFunction()
{
    myGameObject.GetComponent<Timer>().TimerEvent += new Timer.TimerEventHandler(OnComplete);
    myGameObject.GetComponent<Timer>().StartTimer(1, 20);
    // 1 - interval duration (seconds)
    // 20 - interval repetitions.
}

void OnComplete(Timer timerObj, Transform t)
{
   // This method will be called 20 times, each after a duration of 1 second.

   // timerObj - handle to the Timer object.
   // t        - handle to the transform of the GameObject to which the script is attached.

   t.positon += Vector.Up; // Simple operation showing you have a handle to the GameObject.

   if (timerObj.GetCurrentCount() == timerObj.GetTotalCount())
   {
      timerObj.Destroy(); // Removes the script from the GameObject.
   }
}

Notes:

a. Take a closer look at the code to understand all the properties and methods in the class. It is well commented and pretty straight forward.

b. This script should not be used when accurate time computation is required. I am simply using Time.deltaTime every frame to compute elapsed time. Not sure how much precision it has.

c. I haven’t done extensive testing with the script, so bugs may arise. Do let me know if you find any and I shall update it.

I would appreciate any feedback or suggestions on how to improve the script.

Thanks!

388869–13382–$timer_615.cs (3.48 KB)

Can you use System.Timers.Timer instead? They’ve been in .NET for a while, so I imagine they might be in Unity as well. Timer Class (System.Timers) | Microsoft Learn

I think you should be able to with some additional code. I just tailored this script mostly for ease of use with Unity :).