Who Touched It?
Part of the Roblox Game Scripting section of Coddy's Lua journey. Lesson 14 of 25.
hit is a body part, and hit.Parent is the character that body part belongs to. The Players service turns a character into the player who controls it:
local Players = game:GetService("Players")
local player = Players:GetPlayerFromCharacter(hit.Parent)When the toucher is not a character (a ball, a falling brick), GetPlayerFromCharacter returns nil, so check it before you use it:
local player = Players:GetPlayerFromCharacter(hit.Parent)
if player then
print(player.Name .. " found the secret")
endOnce you have the player, you can reach anything inside it, like their scoreboard: player.leaderstats.Coins.Value. Setting a Value with = replaces it.
Challenge
MediumGive 100 Coins to the player who finds the treasure. Every player already has leaderstats with Coins.
- Under the
playerline, addif player then ... end, so a ball causes no error. - Inside it, print the name:
print(player.Name). - Then set
player.leaderstats.Coins.Valueto100.
Press Play and step on the treasure: Output shows your name and Coins jumps to 100. Then Check.
Try it yourself
local Players = game:GetService("Players")
local treasure = script.Parent
treasure.Touched:Connect(function(hit)
local player = Players:GetPlayerFromCharacter(hit.Parent)
-- If it is a player: print their name and set their Coins to 100
end)
All lessons in Roblox Game Scripting
2Loops and Functions
Row of PillarsStaircase BuilderTower BuilderCoin FactoryBlinking LightVanishing Bridge5Your First Game
Your First ObbyPractice on your own: Online Lua compiler