so uh i tried making a script to heal and add speed...but it has no cooldown... local tool = script.Parent
tool.Activated:Connect(function() local humanoid = tool.Parent:FindFirstChild("Humanoid") humanoid.Health = humanoid.MaxHealth humanoid.WalkSpeed = humanoid.WalkSpeed + 10 wait(30) humanoid.WalkSpeed = humanoid.Walkspeed wait(30) end)
I assume the wait(30)
is the cooldown part, and it's not working for a logical reason. Technically what you think would happen is; the code will function, you will wait for 30 seconds, in order ti re-use the weapon. But in reality, when the Activated
event fires again, it ignores the 30 seconds, because it's gonna re-run a whole new part of code. The event fires a first time, it does what it's supposed to do, but it fires again even though 30 seconds haven't passed, because it creates a whole new part of code (or else called a thread) that doesn't have to wait for the first part of code to finish. Your idea is very correct! But what you need to add is a debounce instead of just a lonely wait()
, and this concept is very simple: you make a variable saying whether the event has already fired or not (meaning it's set to false at first because it never ran), and when the event fires it becomes true, and it only goes back to false after a certain amount of time. And of course if a new part of code ran it wouldn't do it's thing while the variable is still true.
local tool = script.Parent local debounce = false --the variable doesn't really have to be called debounce, you can pick any name tool.Activated:Connect(function() if debounce == false then --check if it was never fired debounce = true --say now that it fired local humanoid = tool.Parent:FindFirstChild("Humanoid") humanoid.Health = humanoid.MaxHealth humanoid.WalkSpeed = humanoid.WalkSpeed + 10 wait(30) --wait for 30 seconds debounce = false --and then say the cooldown is over and you can now fire! end --humanoid.WalkSpeed = humanoid.Walkspeed wait(30) --this part seemed very unnessecary end)
You could use debounce. Debounce is a way to cool down code / keep code from running too many times. To answer your question, you could incorporate debounce into your code like so:
--< Variables local debounce = false local cooldown_time = 30 --< Functions tool.Activated:Connect(function() if not debounce then -- Ensuring debounce is false debounce = true local default_walkspeed = humanoid.WalkSpeed local humanoid = tool.Parent:FindFirstChild('Humanoid') humanoid.Health = humanoid.MaxHealth humanoid.WalkSpeed = default_walkspeed + 10 wait(cooldown_time) debounce = false end end)
Hope this answers your question :-) !