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

How do I let this touched event work for only a certain part or a player?

Hello!

I have a touched event script, however the event runs when it gets touched by a part or a player or anything else. How can I make it only runs when a certain part touches it or a player?

The script:

game.Workspace.TouchedEventPart.Touched:Connect(function(hit)
	game.Workspace.Baseplate.BrickColor = BrickColor.new("Sea green")
end)

Thanks for helping!

2 answers

✓ Accepted answer

the proper way to get a player from a touched event is with the :GetPlayerFromCharacter() function. Ex.

workspace.TouchedEventPart.Touched:Connect(function(hit)
	if hit and hit.Parent and game.Players:GetPlayerFromCharacter(hit.Parent) then
		workspace.Baseplate.BrickColor = BrickColor.new("Sea green")
		--no need for game.Workspace, use workspace
	end
end)

This checks if hit exists, and the part that hit the part has a parent, which if a player touched it, should be a body part most of the time. the parent of body parts should always be the player character so then you get player from that character. Note: if you also want to include NPCs in the category of entities that can trigger the event use:

workspace.TouchedEventPart.Touched:Connect(function(hit)
	if hit and hit.Parent and hit.Parent:FindFirstChild("Humanoid") then
		workspace.Baseplate.BrickColor = BrickColor.new("Sea green")
	end
end)

if you only want players to trigger the event, it is encouraged to use :GetPlayerFromCharacter() as opposed to hit.Parent:FindFirstChild("Humanoid")

2 comments

0

Thank you.

0

np

The variable 'hit' in the parentheses refers to the part that was hit. So you'd just need to enclose that line of code in an 'if' statement to ensure it only runs when a specific part is touched.

If you wanted it to work when it touched a part called 'LeftLeg', for example, you'd do this:

game.Workspace.TouchedEventPart.Touched:Connect(function(hit)
	if hit.Name == "LeftLeg" then
		game.Workspace.Baseplate.BrickColor = BrickColor.new("Sea green")
	end
end)

Hope that helps.

1 comment

1

How you do this with a player?

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