I am trying to make it so that when a player touches a part, they get a “coin” which is a currency for the game I am making. The script for the currency is here:
game.Players.PlayerAdded:Connect(function(plr)
local stats = Instance.new("BoolValue",plr)
stats.Name = "leaderstats"
local cash = Instance.new("IntValue",stats)
cash.Name = "Coinn"
cash.Value = 0
end)
Properties of that script ^^^
Parent: ServerScriptService
Disabled: False
No children
Can someone please explain to me the steps I should take in order to create the script?
This can be done with a Touched event, here’s an example
part.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
game.Players:FindFirstChild(hit.Parent.Name).leaderstats.Coins.Value += 1
end
end)
Store all the coins in a folder and then just do this:
local PlayersService = game:GetService("Players")
local CoinsFolder = workspace.NameOfFolder
for _, Coin in ipairs(CoinsFolder:GetChildren()) do
Coin.Touched:Connect(function(Hit)
local Player = PlayersService:GetPlayerFromCharacter(Hit.Parent)
if Player then
Player:WaitForChild("Coinn").Value = Player:WaitForChild("Coinn").Value + 1
end
end)
end
part.Touched:Connect(function(hit)
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if plr then
plr.leaderstats.Coinn.Value = plr.leaderstats.Coinn.Value + 1
end
end)
You should avoid using the parent argument in instance.new because this requires more internal calls thus making it bad for performance. Instead you should change all the necessary properties in the object and then parent the object as the last thing you do. See here: PSA: Don't use Instance.new() with parent argument
As another side note you should be using a folder instead of a BoolValue for creating leaderstats.
For your question you could attach the .Touched event to each part used to increase coins, this event fires wherever the part is touched by another part. Then each time one of these parts is touched check if a player touched the part by checking for a HumanoidRootPart. Once you know a player has touched the part get the player instance from the character using GetPlayerFromCharacter and increase the coins in the leaderstats.