Help needed on a unfunctioning sword script

So i’ve been working on a knight game where you fight with a sword

I want the sword to do damage against anything that has a Humanoid in it

The problem is that whenever i click the sword doesn’t do damage, makes a error but the animation plays.
the error goes by this:
ColossalSword.doDMG:15: attempt to index nil with ‘FindFirstChild’

here is the whole script

local tool = script.Parent
local damage = 35
debounce = false
function swing(hit)
	
	if not debounce then
	
	debounce = true
	
	local anim = Instance.new("Animation")
	anim.AnimationId = "http://www.roblox.com/Asset?ID=11951824285"
	local track
	track = tool.Parent.Humanoid:LoadAnimation(anim)
	track.Priority = Enum.AnimationPriority.Action
	track.Looped = false
	track:Play()
	tool.Handle.SwordSwing:Play()
	local find = hit:FindFirstChild("Humanoid")
	if find then
		find:TakeDamage(damage)
	wait(2)
	
	debounce = false
	end
end

tool.Activated:Connect(swing)

i’ve already tried changing the last lines but haven’t found a solution, i’ve
also tried finding answers on the devforum :frowning:

4 Likes

The error is produced on this row:

That is because the parameter hit is always nil. Why? Because of this:

You run your swing script, which requires the parameter hit to be whatever part is hit. The issue is, tool.Activated:Connect() doesn’t send any arguments to the function swing. You should split the part of the function where you handle the damage into another function.
PS: You are also missing a few ends in the code

Below is an example of how you may split up your code:

... -- Your definitions

function swing()
    ... -- Code to play the animation and set debounce
end

tool.Activated:Connect(swing)

function handleHit(hit)
   if debounce then return end -- Only do stuff if not debounce
   ... -- Get the the part ``hit`` is a part of and deal damage to its humanoid (if one exists)
end

tool.Handle.Hitbox.Touched:Connect(handleHit) -- Assumes the existence of a the part ``Hitbox``
3 Likes

yo i tested the script and it makes no errors! only problem is that
it doesn’t deal any damage.
how can i fix this sir?

2 Likes

If you make a humanoid take damage using a localscript then the damage won’t replicate (show) for other players, so you need to do that from the server. In order to let the server know when you want to deal damage you should use RemoteEvent | Roblox Creator Documentation. To keep things simple you can just send the humanoid they wish to damage.

To know what damage should be dealt you should have Instance Attributes | Roblox Creator Documentation which stores the damage value in order to prevent exploiters from dealing insta-kill damage. You should also implement sanity checks so they cannot damage people from across the map.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.