Menu
CoddyTech

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")
end

Once you have the player, you can reach anything inside it, like their scoreboard: player.leaderstats.Coins.Value. Setting a Value with = replaces it.

challenge icon

Challenge

Medium

Give 100 Coins to the player who finds the treasure. Every player already has leaderstats with Coins.

  1. Under the player line, add if player then ... end, so a ball causes no error.
  2. Inside it, print the name: print(player.Name).
  3. Then set player.leaderstats.Coins.Value to 100.

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

Practice on your own: Online Lua compiler