Roblox objects and events, lesson 24
Touched and finding the player
Goal: Work out which player touched a part.
about 6 min3 practice exercises
Parts have a Touched event. It fires when another part touches them, and passes in that other part.
Here is the catch: a player is not one part. A player's character is a model made of parts (a hand, a foot, a torso). So Touched gives you something like the left foot, and you have to work out who it belongs to.
local Players = game:GetService("Players")
local coin = script.Parent
coin.Touched:Connect(function(hit)
local player = Players:GetPlayerFromCharacter(hit.Parent)
if not player then
return
end
print(player.Name .. " touched the coin")
end)
hit.Parent is the model the touching part belongs to. GetPlayerFromCharacter returns the player if that model is someone's character, and nil if it is not, for example when a loose ball rolls into the coin.
The if not player then return end check is called a guard. It leaves the function early when there is nothing to do, and keeps the main code free of nesting.
A player and their character are different things. The player lasts for the whole session. The character is replaced every time they respawn. Store progress on the player, never on the character.
Try it in Studio
Optional, and the best way to make it stick.
Put the lesson's script inside a Part, press Play and walk into it. Then push another part into it and see that nothing prints.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.