How Do I Make This Script Only Damage The Player I Hit If the Tool Is Activated?

local plr = game.Players:GetPlayerFromCharacter(script.Parent.Parent)

script.Parent.Handle.Touched:Connect(function(touch)

if script.Parent.CanDamage.Value == true then

	if not touch.Parent:FindFirstChild("Humanoid") then return end

	script.Parent.CanDamage.Value = false

	local plr = game.Players:GetPlayerFromCharacter(script.Parent.Parent)
	touch.Parent.Humanoid:TakeDamage(plr.leaderstats.Power.Value)

	if touch.Parent.Humanoid.Health < 1 then

		local plr = game.Players:GetPlayerFromCharacter(script.Parent.Parent)
		plr.leaderstats.Kills.Value = plr.leaderstats.Kills.Value + 1

	end

	wait(1)

		script.Parent.CanDamage.Value = true
end

end)

The thing is, with this process, the event functions that you put up in the script, they don’t just go when a certain requirement is met.

If an event is posted in a script, it will always be there, waiting for activation. In your case, the event won’t just turn off when the CanDamage bool is equal to false.

What you should do is disconnect the event when you’re done with it. This code should give you your answer:

local plr = game.Players:GetPlayerFromCharacter(script.Parent.Parent)
local TouchEventConnection
function OnTouch(touch)
if script.Parent.CanDamage.Value == true then

if not touch.Parent:FindFirstChild("Humanoid") then return end

script.Parent.CanDamage.Value = false

local plr = game.Players:GetPlayerFromCharacter(script.Parent.Parent)
touch.Parent.Humanoid:TakeDamage(plr.leaderstats.Power.Value)

if touch.Parent.Humanoid.Health < 1 then

local plr = game.Players:GetPlayerFromCharacter(script.Parent.Parent)
plr.leaderstats.Kills.Value = plr.leaderstats.Kills.Value + 1

end

wait(1)

script.Parent.CanDamage.Value = true
end
end

And when the tool is activated, you could run this code where it checks whether the CanDamage bool is true or not. This code should set an example:

tool.Activated:Connect(function()
if CanDamage ==  true then
TouchEventConnection = script.Parent.Handle.Touched:Connect(OnTouch(touch))
elseif TouchEventConnection ~= nil and CanDamage == false then
TouchEventConnection:Disconnect()
end

This is how you handle disconnection and connection. I hope this helps out, if it’s too detailed and you need a better explanation, let me know.

1 Like