Im having this script run an action by a player which is used to gather stuff from the ground. But Im adding a remote event to cancel the action midway.
I tried to make the whole action in a coroutine that could be canceled by the cancelActionEvent.OnServerEvent. My main problem is that I when I try to close it, it prints ''cannot resume dead coroutine. And moreover, the whole function is called everytime a player starts an action. So if they start the action, cancels it and restarts, it will create 2 cancelActionEvent.OnServerEvent detection therefor printing “cancelling (x2)”
function action(plr,model,tool,track,reward,amount,prompt)
print("action")
local char = plr.Character
local hRP = char.HumanoidRootPart
local hum = char.Humanoid
local clone
local actionRoutine = coroutine.create(function()
animationRemote:FireAllClients(track)
cameraRemote:FireClient(plr,true)
hRP.Anchored = true
hum.AutoRotate = false
clone = tool:Clone()
wait(1/3)
hum:UnequipTools()
clone.Parent = char
local lookpart = model:FindFirstChild("BottomPart") or model:FindFirstChild("HumanoidRootPart")
hRP.CFrame = CFrame.lookAt(hRP.Position, Vector3.new(lookpart.Position.X, hRP.Position.Y, lookpart.Position.Z))
wait(13/3)
clone:Destroy()
wait(1/3)
plr.leaderstats:FindFirstChild(reward).Value += amount
hRP.Anchored = false
hum.AutoRotate = true
cameraRemote:FireClient(plr,false)
plr.leaderstats.ActionTag.Value = false
ActionManager.fadeOut(model)
end)
coroutine.resume(actionRoutine)
print("Resumed")
cancelActionEvent.OnServerEvent:Connect(function(requester)
if requester == plr then
print("cancelling")
coroutine.close(actionRoutine)
hRP.Anchored = false
hum.AutoRotate = true
animationRemote:FireAllClients("stop")
cameraRemote:FireClient(plr,false)
clone:Destroy()
plr.leaderstats.ActionTag.Value = false
prompt.Enabled = true
end
end)
end
Output:

DONT BOTHER ABOUT: '‘Starting the game’'