Sword does damage without clicking

Custom weapon I have made deals damage to bosses/enemies without me clicking on them

local tool = script.Parent
local handle = tool.Handle.Blade
local damage = 10
local debounce = false
tool.Activated:Connect(function()
	handle.Touched:Connect(function(hit)
		if hit.Parent:FindFirstChild("Boss") and hit.Parent:FindFirstChild("Boss"):IsA("Humanoid") then
			if not debounce then
				debounce = true
				hit.Parent.Boss.Health = hit.Parent.Boss.Health - damage
				wait(0.5)
				debounce = false
			end
		end
	end)
end)
		

this is the weapons damage script I’ve had this issue for quite the long time any help would be appreciated!

1 Like

A few notes:
1.What is Boss? A model?
2.Use task.wait() instead of wait.
3.This line hit.Parent.Boss.Health = hit.Parent.Boss.Health - damage can be:
hit.Parent.Boss.Health -= damage
4.One issue I noticed, is that Health is a property of Humanoid, I guess you named the npc’s humanoid Boss?

3 Likes

Yes the boss is a model, Alright I’ll check out 2 and 3 and yes the humanoid is called boss so it doesnt hurt normal players and only hurts bosses / monsters

1 Like

Makes sense, tho you dont need to do that, you could simply make an if statement to check if the hit represents a player’s body descendant or not.

2 Likes

Edit: Fixed my example because the debounce variable was not synced up correctly, which would have resulted in people not getting damaged when intended. The logic should handle damage correctly now.

When you activate the tool, you connect the Touched event to a function. This connection will last even after the code finishes. Meaning that the touched event function will run when the tool touches something even if it’s not activated. To fix this, I recommend separating the logic for what happens when the tool is activated and when the tool hits something. Then I would add a bool variable for when the tool is activated or not. Here’s my example using your script:

local tool = script.Parent
local handle = tool.Handle.Blade
local damage = 10
local debounce = false
local attackTime = .5
local attacking = false

tool.Activated:Connect(function()
	attacking = true
	wait(attackTime)
	attacking = false
	debounce = false
end)

handle.Touched:Connect(function(hit)
	if attacking and hit.Parent:FindFirstChild("Boss") and hit.Parent:FindFirstChild("Boss"):IsA("Humanoid") then
		if not debounce then
			debounce = true
			hit.Parent.Boss.Health = hit.Parent.Boss.Health - damage
		end
	end
end)

This way, the Touched event function has an if statement that only run when the variable attacking is true and attacking is only true when the tool is activated. The variable attackLength specifies how long the tool should be able to damage after initial activation.

Hope this helps!

2 Likes

Oh wow! Thank you, You have taught me something new and helped me this is awesome thanks! It works, I can now finally pass the stump I have been on thank you.

2 Likes