How to wait in defold

Im trying to make a game which needs a wait similar to roblox. I understand there are timer.delay that i could probably chain together, but i need a lot of them for readability. I mainly need it for things like cutscenes and text dialouge. if there isnt a way, is there some way to make a function myself that pauses for a few seconds before going on to the next line?

1 Like

If you have a lot of them, maybe make a Lua table with all sequence parts e.g. :

Animations = {
[0] = { animation = function() ... end, delay = 2 }
[1] = ...
...
}

and then write a simple function to traverse through all and put them in a chain (use callback for next function)?

Ok thats probably a better idea for cutscenes but I still need to have a wait function for other parts of the game. Do you know if there’s a way I could make a function something like wait(seconds)

1 Like

As you wrote, in Defold you have timer.delay(). Basic usage:

timer.delay(1, false, function()
    ...
end)

This will trigger your function after 1 second once (false - no repeating)

timer.delay(1, true, function()
    ...
end)

This will trigger your function every 1 second (true - repeating)


There is an asset called “Def Timeline” that might be useful for you, but it’s pretty old (let me know if it’s working or not if you decide to try it :wink: ):

My go-to solution would be to use a coroutine:

-- this wraps timer.delay() and yields the running coroutine until the
-- timer triggers
local function wait(seconds)
	local co = coroutine.running()
	assert(co, "Must be called from within a coroutine")
	timer.delay(seconds, false, function()
		coroutine.resume()
	end)
	coroutine.yield()
end


-- this is how you use it
function init(self)
	-- wrap a function in a coroutine and run it immediately
	coroutine.wrap(function()
		print("hello")
		wait(1)
		print("one second has elapsed")
		wait(0.5)
		print("half a second has elapsed")
	)() -- <-- this is the "run immediately part"
end
8 Likes