You can use Coroutines to play, pause, and stop functions that are running.
First, let’s define a variable named CoroutineObject
.
local CoroutineObject
We need to store the function that is called as it’s own separate object. And once the code was done, set the CoroutineObject
to nothing.
local function Func(Player, Target, PlayerName)
if Character["Main Pet."].Value == false and PlayerName == Owner then
Character:SetAttribute("Attacking", true)
Character:SetAttribute("Following", false)
Character:SetAttribute("Target", Target.Name)
Attack(Target)
Character:GetAttribute("Attacking", false)
FollowPlayer()
end
CoroutineObject = nil
end
When the event was fired, we set the CoroutineObject
to a Thread. A thread is simply an object that runs code. And this thread will run the Func
function.
game.ReplicatedStorage["Remote events."]["Attack resever."].OnServerEvent:Connect(function(Player, Target, PlayerName)
CoroutineObject = coroutine.create(Func)
coroutine.resume(CoroutineObject, Player, Target, PlayerName)
end)
We can check if the CoroutineObject
is equal to anything other than nothing. And if it is, we stop whatever the previous function was doing, and begin a new one.
game.ReplicatedStorage["Remote events."]["Attack resever."].OnServerEvent:Connect(function(Player, Target, PlayerName)
if CoroutineObject then
coroutine.close(CoroutineObject)
end
CoroutineObject = coroutine.create(Func)
coroutine.resume(CoroutineObject, Player, Target, PlayerName)
end)
Full code:
local function Attack(Target)
if FunctionRunning then return end
FunctionRunning = true
repeat
wait(0.5)
print(Target)
NoobModule:Attack(Character, Target)
until Attacking ~= true or Following == true or Target.Humanoid.Health == 0 or FunctionRunning == false
FunctionRunning = false
end
local CoroutineObject
local function Func(Player, Target, PlayerName)
if Character["Main Pet."].Value == false and PlayerName == Owner then
Character:SetAttribute("Attacking", true)
Character:SetAttribute("Following", false)
Character:SetAttribute("Target", Target.Name)
Attack(Target)
Character:GetAttribute("Attacking", false)
FollowPlayer()
end
CoroutineObject = nil
end
game.ReplicatedStorage["Remote events."]["Attack resever."].OnServerEvent:Connect(function(Player, Target, PlayerName)
if CoroutineObject then
coroutine.close(CoroutineObject)
end
CoroutineObject = coroutine.create(Func)
coroutine.resume(CoroutineObject, Player, Target, PlayerName)
end)