Coin Respawn
Part of the Roblox Game Scripting section of Coddy's Lua journey. Lesson 16 of 25.
Each coin now gives 1, once. A real coin should disappear, then come back so it can be collected again.
Transparency = 1 hides a part, but it still fires Touched. CanTouch = false makes a part stop firing Touched until it is set back to true.
To bring it back, wait inside the Touched function and undo the changes. task.wait pauses only this function, so other touches keep arriving and are ignored while the debounce is true:
local used = false
pad.Touched:Connect(function(hit)
if not used then
used = true
pad.Transparency = 0.5
task.wait(5)
pad.Transparency = 0
used = false
end
end)The pad fades for 5 seconds after a touch, then it is back and ready again.
Challenge
MediumMake a collected coin hide, then come back 3 seconds later.
- After the line that adds the Coin, hide it:
coin.Transparency = 1andcoin.CanTouch = false. - Then
task.wait(3)and show it again:Transparency0,CanTouchtrue. - Last, set
collected = falseso it can be collected again.
Press Play and walk through a coin: it vanishes and comes back 3 seconds later. Then Check.
Try it yourself
local Players = game:GetService("Players")
local coins = workspace.Coins
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local coinsValue = Instance.new("IntValue")
coinsValue.Name = "Coins"
coinsValue.Value = 0
coinsValue.Parent = leaderstats
end)
for _, coin in coins:GetChildren() do
local collected = false
coin.Touched:Connect(function(hit)
local player = Players:GetPlayerFromCharacter(hit.Parent)
if player and not collected then
collected = true
player.leaderstats.Coins.Value += 1
end
end)
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