Coroutine not working as I thought it would?

Hello there!

I use coroutines with great frequency, in other to make things run inside of my code independently, especially for cooldowns.

I’m using a coroutine to control the cooldown of a Lunge attack, which should only run if a player is blocking. The problem I’m having is that even though I wrapped it around a coroutine, the wait() function is holding the rest of my script back, so I can’t attack while the blocking cooldown is in effect.

Lunge Function:

local function ReplicateBlock()
	local noDisturbance = coroutine.resume(coroutine.create(function()
		if not isBlocking.Value and not isAttacking2 and not canDamage and not blockCooldown and not isAttacking.Value and canBlock.Value then
			
		blockCooldown = true
		isBlocking.Value = true
		canDamage = true
		wplayer.Humanoid.WalkSpeed = 10
			
		wait(1)
			
		local bodyVelocity = Instance.new("BodyVelocity", wplayer.Torso)
			
		repeat wait() until wplayer.Torso:FindFirstChild("BodyVelocity")
			
		bodyVelocity.MaxForce = Vector3.new(40000, 40000, 40000)
		bodyVelocity.P = 40000
		bodyVelocity.Velocity = wplayer.HumanoidRootPart.CFrame.LookVector * 50
			
		wait(.3)
			
		wplayer.Humanoid.WalkSpeed = 16
			
		bodyVelocity:Destroy()
		wait(9)
		isBlocking.Value = false
		blockCooldown = false
		canBlock.Value = false
			
		end
	end))
end
1 Like

Try using coroutine.wrap

local function attack(eeeee)
print("hi")
end
coroutine.wrap(attack)(eeeee)
1 Like

coroutine.wrap does the same thing as coroutine.resume(coroutine.create())) but doesn’t required it to be called.

Could it be dependent on how your calling the function, From what I see, you have a local function in a local function

local function ReplicateBlock()
local noDisturbance = coroutine.resume(coroutine.create(function()

Is there a reason for both functions?

1 Like

If I used coroutine.wrap there wouldn’t be a need for two functions since I could just call the wrap whenever I wanted the function to run.

If I use coroutine.resume(coroutine.create(function())) it runs the moment it is read and cannot be called again like a wrap, that’s why it’s inside of a function.

1 Like