How does this script work

I’ve been trying to figure out how to damage another player with a sword instead of the player and other player taking damage. I came across gamer m8’s tutorial on making a sword and saw his script for it. Though I don’t really understand it a lot, could someone clarify? Thanks.

local tool = script.Parent

local function onTouch(partOther)
	
	local humanOther = partOther.Parent:FindFirstChild("Humanoid")
	
	if not humanOther then return end
	
	if humanOther.Parent == tool then return end
	
	humanOther:Takedamage(5)
end


edit: I decided to test if it even works and put it in my script. Though it didnt work and got the error message:  18:15:32.454  Attempt to connect failed: Passed value is not a function 
Part of the script with gamer m8's script

function swingnormal()
local swingn = Instance.new(“Animation”)
swingn.AnimationId = “rbxassetid://7193950823”

local whamn = humanoid:LoadAnimation(swingn)
whamn:Play()

 local function onTouch(partOther)

	local humanOther = partOther.Parent:FindFirstChild("Humanoid")

	if not humanOther then return end

	if humanOther.Parent == tool then return end

	humanOther:Takedamage(5)
end

end

Mouse.Button1Down:Connect(swingnormal())

The Tool is the parent of the script. onTouch is the local function that I assume is supposed to be connected to run on the event when the hitbox is touched (I don’t see that part of the code.) It has one parameter, partOther which is the part that was detected to touch the hitbox. Every time the hitbox hits an enemy, the passed parameter is always a descendant of that enemy (humanoidrootpart, head etc.) or anything that identifies as a collision is always a some sort of part. The local humanOther checks if the part that is hit has a parent and a humanoid, basically checking if what the hitbox collided with is a enemy. If not, then the code returns and nothing happens. Then, since the humanOther is a detected player, TakeDamage() (you spelled wrong) literally takes health away from the enemy.

I have to say, I can’t make sense of where your code is, because you now play an animation when the mouse is clicked. That should be in a local script ? Or did you put it with your script?

1 Like

Ya my bad made it confusing. And ignore the last part about it not working I messed up on my side. Thanks for explaining.

Alright, this is a very smart way, so let me break it down.

This line takes the object we hit, and tries to find a humanoid (to see if they are a player)

We wanna make sure it’s a humanoid, and not a random part.

This is the main line. tool.Parent is equal to the character, right? And if humanOther.Parent is another character, we can check. If those two are the same, that means we are trying to deal damage to the player, not enemy.

Change this to TakeDamage, just smol nitpick :slight_smile:

2 Likes