Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 6 years ago

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

Log in to vote
0
Answered by 6 years ago

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")

0
Thank you. kees31ALT 5 — 6y
0
np theking48989987 2147 — 6y
Ad
Log in to vote
0
Answered by 6 years ago

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
How you do this with a player? kees31ALT 5 — 6y

Answer this question