So I was trying to make a health kit that despawns from 10 seconds when you touch it, but since the touched event is happening a lottttt of times per second, not only does it heal the player much more than it should but it’s also grabeable multiple times. I have no idea how to stop it from firing multiple times.
Here’s my code:
available = true
while true do
if available then
script.Parent.healpart.Transparency = 0
script.Parent.healpart.Decal.Transparency = 0
script.Parent.healpart.Touched:Connect(function(hit)
if hit.Parent.Humanoid then
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health + 50
script.Parent.healsound:Play()
script.Parent.healpart.Transparency = 1
script.Parent.healpart.Decal.Transparency = 1
available = false
end
end)
else
wait(10)
available = true
end
wait(0.1)
end
Try putting the “available = false” debounce right after “if hit.Parent.Humanoid then” instead of having the debounce change after all the healing stuff occurs.
Additionally, you shouldn’t have a touched event running in a loop, which is most likely the reason it is firing a lot how you described. Just have the touched event on its own as a function, and it will still be fine.
I’ll don’t know what that means, I’ll look into it, but thanks a lot either way! (I’m making this game to learn how to do new things in Roblox Studio so these replies are really useful)
Actually putting an event inside a loop does not make it fire multiple times but rather creates unnecessary connections which can lead to your game using more resources than required.
This is why it is often suggested to disconnect an event after it is no longer of use(in most cases this is not needed though).
available = true
while true do
if available == true then
available = false
script.Parent.healpart.Transparency = 0
script.Parent.healpart.Decal.Transparency = 0
script.Parent.healpart.Touched:Connect(function(hit)
if hit.Parent.Humanoid then
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health + 50
script.Parent.healsound:Play()
script.Parent.healpart.Transparency = 1
script.Parent.healpart.Decal.Transparency = 1
available = true
end
end)
else
wait(10)
available = true
end
wait()
end
I tried (the answer to) this, it worked for the first time, but for some reason it still broke after the trigger was re-activated (debounce set back to true at the end) and fired twice
even worse, it counts up every time instead, so the 3rd touch it activates thrice