How to use coroutine?

Hello, I am making a system where player gets anchored and after a while get un anchored. I don’t want to use wait as I want the script to keep going. And as far as I know coroutine would be the solution but idk how to use it.

	for i,v in pairs(game.Players:GetChildren()) do
		if v.IsInRound.Value == true then
			local character = v.Character or v.CharacterAdded:Wait()
			character:WaitForChild("Torso").Anchored = true
			coroutine.create(function()
				wait(5)
				character:WaitForChild("Torso").Anchored = false
			end)
		end
	end

Here’s my script snippet

Cheers

You created a coroutine thread, but didn’t started it’s execution. Add coroutine.resume before coroutine.create, like this:

coroutine.resume(coroutine.create(function()
				wait(5)
				character:WaitForChild("Torso").Anchored = false
			end))

or you could just use something like task.spawn() as an alternative, which automatically adds the thread on execution list after you call it

ohhhhhhhhhhhhhhhhh ok thanks can you tell me how to use task.spawn just in case? thanks

It’s basically the same as coroutine.resume but also accepts a standalone function in case you haven’t created a thread, basically doing both coroutine.create and coroutine.resume in one go through task scheduler system

ah i see thank you. bye have a good day

You can also create a coroutine and run it via:

coroutine.wrap(function()
    -- code here
end)() -- notice the "()", thats how we are running this coroutine

----------------------------------------------------------

local coro = coroutine.wrap(function()
    print("i have a function")
end)

coro()

-- >> i have a function

This is basically a coroutine with a function which can be ran like a function.

Coroutine API documentation: coroutine | Roblox Creator Documentation