Trouble with making a sword damage things

I’m trying to make a system where if you use a sword on an enemy, it damages the enemy. I made it so that if the sword touches the enemy, the enemy takes damage. Now I want it so that the enemy only takes damage if the sword touches it and the player actually uses the sword. Here is my current script:

local burger = script.Parent

for i,part in pairs(burger:GetChildren()) do
	if part:IsA("MeshPart") then
		print("Part is mesh")
		part.Touched:Connect(function(otherPart)
			print(part.Name.." got touched")
			if otherPart.Parent.Name == "Sword" and otherPart.Parent:IsA("Tool") then
				print("yes sword")
				local health = part.Parent:GetAttribute("Health")
				print(health)
				health = health - 100
				part.Parent:SetAttribute("Health", health)
				print(health)
				if health == 0 then
					print("destroyed")
				end
			end
		end)
	end
	print("next child")
end

How would I do this?

When the player uses the sword, record the current time by calling time(). When the sword hits, check how long its been since the sword was used by comparing it to the recorded time. If the hit occured within a certain window you choose, allow the hit to be counted.

It is probably more efficient to detect from the sword if it hit a character.

local sword = script.Parent --The parent of this server script is a tool instance, which contains the sword

sword.Activated:Connect(function()
	--Change rotation/potion of sword if neccecary
	
	local connection
	connection = sword:FindFirstChildWhichIsA("BasePart").Touched:Connect(function(hit)
		local character = hit.Parent
		local humanoid = hit:FindFirstChildOfClass("Humanoid")
		if humanoid == nil then
			return
		end
		connection:Disconnect() --Stops another hit from happening until reload
		humanoid.Health -= 20 --Amount of damage per hit
	end)
	
	wait(2)
	connection:Disconnect()
	--Return rotation/potion of sword
end)

--Put sword in starter pack
3 Likes

This is a great solution, but there is one problem. The wait time is enough for me and my computer to remove the health before it disconnects, but for laggier devices, there may need to be more wait time. How do I fix this. Also, I would like there to be a cooldown for hits. How could I do this?

have you tried using the raycast hitbox?