This script is supposed to damage a player by taking 5 lives off of it every 10 seconds - but it kills the player almost instantly. What gives?
function onTouched(hit)
local human = hit.Parent:findFirstChild("Humanoid")
local canDamage = true
if (human ~= nil) then
if canDamage == true then
canDamage = false
human.Health = human.Health - 5 -- Change the amount to change the damage.
wait(10)
canDamage = true
end
end
end
script.Parent.Touched:connect(onTouched)
Your debounce won’t work because you set the canDamage to true when they touch it.
Also, a few things:
I see no reason to use a global function, perhaps replace it with a local one.
findFirstChild is deprecated, use FindFirstChild.
You can use the Humanoid:TakeDamage(number) function instead, since that’s kind of that it is for, IMO.
:connect() is also deprecated, use :Connect() instead.
That being said, here’s an example:
local Debounce = false
local function onTouched(hit)
if Debounce then return end
Debounce = true
local Humanoid = hit.Parent:FindFirstChild('Humanoid')
if Humanoid then
Humanoid:TakeDamage(50)
end
wait(10)
Debounce = false
end
script.Parent.Touched:Connect(onTouched)
Or, if you only want it to be for every player, you can set a debounce for the player who touches it instead of a global debounce:
local Debounce = false
local Debounces = {}
local function onTouched(hit)
local Player = game:GetService('Players'):GetPlayerFromCharacter(hit.Parent)
if Player then
if table.find(Debounces, Player.UserId) then return end
table.insert(Debounces, Player.UserId)
local Character = Player.Character
if Character then
local Humanoid = Character:FindFirstChild('Humanoid')
if Humanoid then
Humanoid:TakeDamage(50)
end
end
wait(10)
table.remove(Debounces, table.find(Debounces, Player.UserId))
end
end
script.Parent.Touched:Connect(onTouched)
Yeah like @Xacima said, since you have canDamage inside of the touched connection it will always be true when a player touches it. So what you need to do is move it outside the function.
local canDamage = true
function onTouched()
if canDamage then
canDamage = false
wait(10)
canDamage = true
end
end
It would look something like this, of course make sure to add the rest of your code.