Detecting When a Player Touches a Part (Quick Tutorial #5)

This is a very quick read on how to detect when a player touches a part in Roblox Studio!

Short Breakdown

Here are some notes / requirements for the tutorial to work!

  • Use a script inside the part or in ServerScriptService
  • The part must have CanCollide and Anchored set correctly
  • Use the .Touched event to detect the touch
Actual Tutorial

First, declare the part you want to detect touches on:

local part = workspace:WaitForChild("MyPart")

Next, connect a function to the .Touched event:

part.Touched:Connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if player then
        print(player.Name .. " touched the part!")
    end
end)

What’s happening here?

Hit is the object that touched the part.

We check if the touching object belongs to a player’s character by getting the player from the hit object’s parent!

If it’s a player, we print their name in the output.

And you’re done! Now whenever a player touches the part, you’ll see their name in the output! :wave: :sparkles:

Script For Lazy Readers
local part = workspace:WaitForChild("MyPart")

part.Touched:Connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if player then
        print(player.Name .. " touched the part!")
    end
end)

Thank you for reading, and please drop me a follow on Roblox! :woot:

2 Likes