Who Touched It?
Part of the Roblox Game Scripting section of Coddy's Lua journey. Lesson 14 of 24.
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
MediumThe glowing pad is treasure, and this script is inside it. Every player already has leaderstats with Coins at 0.
When a player touches the treasure, print their name and set their Coins to 100. Things that are not players must not cause an error.
Press Play, step on it and watch the scoreboard, 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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