Waiting with YaTime

If you want to control the timing of your project you can use YaTime. This class will enable you to wait for set amounts of time and run scripts after that time has passed. YaTime is defined like this:

YaTime_TypeDefinitions
The YaTimeComponent Type Def

Prerequisites:

It is also helpful if you have checked out the example section for the Event Helper, because working with YaTime is very similar.

Wait for n Seconds

From the type definitions we can find out that YaTimeComponent provides a WaitFor(seconds) function that takes a number as an input and returns a TimeEventContainer. Currently, we can’t add the YaTimeComponent to our assets, but we can access the functionality from everywhere using the YaTime accessor. The basic usage looks like this:

local eventContainer = YaTime:WaitFor(5)

This will wait for 5 seconds, and then nothing else. To use the timer, we need to subscribe to the event that is triggered after the given time has passed.

Subscribe to TimeEvents

To be able to subscribe to the event provided by YaTimeComponent, we need to use the EventHelper. We will be using these two helper functions:

local AddListener = EventHelper.AddListener

local RemoveListener = EventHelper.RemoveListener

Then we will define a handler function where we can execute whatever we want to be exectued after our given time has passed, and remove the event listener again.

local function handler()

print('Received Time Event - DO THINGS HERE -')

RemoveListener(eventContainer, "TimeEvent", handler)

end

After we have defined the handler, we can subscribe to the time event by passing the EventContainer returned by WaitFor(), the event contained in the EventContainer and the handler that gets exectued when the event is triggered:

AddListener(eventContainer, "TimeEvent", handler)

Full Example

To get this working straight away, paste this into a new script you have added to an asset in your scene:

local AddListener = EventHelper.AddListener

local RemoveListener = EventHelper.RemoveListener

local eventContainer = YaTime:WaitFor(5)

local function handler()

print('Received Time Event - DO THINGS HERE -')

RemoveListener(eventContainer, "TimeEvent", handler)

end

AddListener(eventContainer, "TimeEvent", handler)

After 5 seconds, you should see a message in your console. Replace print() with whatever you want to execute after the waiting time.

That’s it, have fun creating :slight_smile:

3 Likes