Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is this endlessly killing?

Hi, I am confused on something:

I am making a tool that when activated, it detects for another player hitting the player who activated it and if it does detect someone, it take 30 health away. But, when activated once, it constantly detects for it. Here is my script:

--Outside Variables--
local Animation = script.Parent:WaitForChild("Animation")
local cd = false
script.Parent.Activated:Connect(function()
	if cd == false then --check for cooldown
	--first code--
		cd = true		
	--variables--
		local Humanoid = script.Parent.Parent:WaitForChild("Humanoid")
		local loadedAnimation = Humanoid:LoadAnimation(Animation)
		local Root = script.Parent.Parent:WaitForChild("HumanoidRootPart")
		local sound = script.Parent:WaitForChild("OverDrive")
	--code-- 
		sound:Play()
		loadedAnimation:Play()
		Root.Anchored = true
		wait(0.05) -- To minimize chance of bugging--
	--touched event--
		Root.Touched:Connect(function(hit)
			local char = hit.Parent
			local Humanoid = char:WaitForChild("Humanoid")
			Humanoid.Health = Humanoid.Health - 30
		end)
	end

How can I fix this? Thanks.

3 comments

0

You used the debounce in the wrong place.

0

Where should i use it?

0

You might need to increase wait, 0.05 is very fast and in this case staying on it for 0.2 seconds is a instant kill.

2 answers

✓ Accepted answer

Actually, I used to do this and got the exact same problem as you. Here's what I did:

--make a table for all the players that the tool touched

local TouchedPlayers = {}	--this variable should go at the top of the script before the main code is written

Root.Touched:Connect(function(hit)
	       	local char = hit.Parent
		local Humanoid = char:WaitForChild("Humanoid")
	        Humanoid.Health = Humanoid.Health - 30
		TouchedPlayers[char] = true --tell the script that, "Hey, I just touched this person and I should not touch it again unless cooldown is over"
		wait(4) --change it to your preffered cooldown time
		TouchedPlayers[char] = nil --cooldown is over
end)

and at line 5, you could do:

if cd == false and not TouchedPlayers[char] then
	--stuff happens here
end

Because you need to check whether there is TouchedPlayers[char] in line 5, the Root.Touched function should be moved up the script.

What was your script?

is your script located in workspace

1 comment

0

oh, it was in a tool as a script (not localScript)

This discussion is preserved as it was. New answers, comments, and votes are closed.