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

How can I use the Touched and TouchEnded Events to only work when a player touches said part?

Asked by 6 years ago

I basically decided to make a 5x5 floor where each part would change brick color when a player walked on it. I was able to sort of make this happen... but as soon as I tested it I realized that the tiles also recognized the baseplate and each other as a "touch". So the end result was a bunch of tiles constantly changing back and forth between colors in an ugly mess. Is there way to write it so that it only fires when a player touches the part and not other things? Here's what it looked like, I basically just had 25 versions of this with the "partX" name changed in it each time:

game.Workspace.part1.Touched:Connect(function(hit)
    game.Workspace.part1.BrickColor = BrickColor.new("Electric blue")
end)

game.Workspace.part1.TouchEnded:Connect(function(miss)
    game.Workspace.part1.BrickColor = BrickColor.new("Institutional white")
end)

There's probably a much more efficient way to accomplish this, but this is literally my third day scripting and I just got through all of AlvinBlox's YouTube tutorials. Hopefully there's a not too complicated way of doing this.

Thanks

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

Check for a humanoid since all players have a humanoid.



game.Workspace.part1.Touched:Connect(function(hit) --Define humanoid humanoid = hit.Parent:FindFirstChild("Humanoid") if humanoid then game.Workspace.part1.BrickColor = BrickColor.new("Electric blue") end end)

Also, to make your script much more efficient such that you do not have to change each part's name, try doing: (insert script as a child of the part)

script.Parent.Touched:Connect(function(hit)
--Define humanoid
humanoid = hit.Parent:FindFirstChild("Humanoid")
    if humanoid then
         game.Workspace.part1.BrickColor = BrickColor.new("Electric blue")
    end
end)
0
FYI, that won't help much at all in the way of efficiency, but it will make it more clean and reduce the amount of hard-coding he has. JarodOfOrbiter 10 — 6y
0
I do agree, also I refer to efficient as doing much less work on his part, which saves time, definitely making it much more efficient. AbandonedRick 112 — 6y
Ad

Answer this question