Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Basic Scripting Question for Touched Event?

Sorry if this is a stupid question but I am new to scripting I have some confusion about the touched event.

So if I want to make a player lose health when he touches a block, I use this:

script.Parent.Touched:Connect(function(hit)
     local hum = hit.Parent:FindFirstChild("Humanoid")
	if hit.Parent:FindFirstChild("Humanoid")then
			hum.Health = hum.Health - 10

        end
end

I am just confused as to how this works. How does the block search for the "Humanoid". Also the parameter "hit" do we include this as it is a only local to the block? If anyone could help me understand, perhaps explain how this all functions. I would really appreciate it. Thank you.

1 answer

✓ Accepted answer

"hit" is part that touched the block. Lets say player touched it with leg. There is variable hum to find humanoid as humanoid is placed inside character when you do hit.Parent it would bring us to character and FindFirstChild() finds first child using a string. After that code checks if there is humanoid because if other part touches it you couldn't take its health because it doesn't have it. If it does have humanoid then it takes 10 health. Note: line 2 should go after line 3 because if there isn't humanoid it would give error. You should first check if there is beforee.

3 comments

0

Ok so when the player touches the block, is the script applied to them and thats how hit is able to find the "FindFirstChild" "Humanoid"?

0

Yes script is applied to one part of their body and that's how you get the player. In case you want to get player from it you would do

0

local Player = game.Players:GetPlayerFromCharacter(hit.Parent)

This discussion is preserved as it was. New answers, comments, and votes are closed.