I’m facing a problem which I can’t seem to solve, I’m still a beginner when it comes to coroutines and I still need help for this one
local rs = game:GetService("ReplicatedStorage")
local fighting = false
coroutine.wrap(function()
while true do
if fighting == false then
print("paused")
wait()
elseif fighting == true then
print("attacked!")
wait(15)
end
end
end)()
rs.Remotes.Fight.OnClientEvent:Connect(function()
fighting = true
end)
rs.Remotes.Quit.OnClientEvent:Connect(function()
fighting = false
end)
How would I make it that it stops the wait(15) immediately after “fighting” is set to false?
4 Likes
local fighting = false
local stopthread = nil
coroutine.wrap(function()
while true do
if fighting == false then
print("paused")
task.wait()
elseif fighting == true then
stopthread = task.defer(function()
print("attacked!")
task.wait(15)
if stopthread then
task.cancel(stopthread)
end
end)
end
end
end)()
rs.Remotes.Fight.OnClientEvent:Connect(function()
fighting = true
end)
rs.Remotes.Quit.OnClientEvent:Connect(function()
fighting = false
if stopthread then
task.cancel(stopthread)
stopthread = nil
end
end)
this should work not sure didnt test!
1 Like
First of all. why would you ever use wait
inside a coroutine
? It is not recommended as there are more efficient options such as couroutine.yield
, so could u pls tell me what ur tryig to achieve so I could provide a more substantial solution?
1 Like
You shouldn’t be using polling mechanism like these anyways.
But I believe you can use coroutine.close
or task.cancel