I’m really in need with help with a script to do with collecting a coin. I want the script to detect when someone touches it, the coin stat will go up by +1.
Here is the script:
local players = game:GetService("Players")
local coin = script.Parent
coin.Touched:Connect(function(char)
local humanoid = char.Parent:FindFirstChild("Humanoid")
if humanoid then
local player = players:GetPlayerFromCharacter(humanoid)
local leaderstats = player:WaitForChild("leaderstats")
if leaderstats then
local coins = leaderstats:FindFirstChild("Coins")
if coins then
coins.Value += 1
script.Parent:Destroy()
end
end
end
end)
I also really suggest you use a single script for all coins, because right now it looks like the script is for a single coin, and all coins have a script inside of it. It is way easier to use a single script and you keep your game more organized.
I wouldn’t use humanoid at all for this since it’s only being used to find the player’s character so that you can pass it into GetPlayerFromCharacter(). Instead, I would take the following approach:
coin.Touched:Connect(function(hit)
local player = players:GetPlayerFromCharacter(hit.Parent)
if not player then return end
-- Other code here
end)
It just makes your code a bit cleaner and more readable, but will ultimately serve the same purpose.
I have rewrited the code for you and it should look like this :
local Players = game:GetService("Players")
local Coin = script.Parent --the coin
coin.Touched:Connect(function(OtherPart) --OtherPart is the reference to the part that your coin is touching
local Player = Players:GetPlayerFromCharacter(OtherPart.Parent) --The other part would be like one of the character arm or leg
if Player then --if player exist
local Leaderstats = player:WaitForChild("leaderstats") --Player's leaderstats
local Coins = leaderstats:FindFirstChild("Coins") --Coins leaderstats value object
Coins.Value += 1 --add 1 to the value of your object value Coins
Coin:Destroy() --destroy the part coin
end
end)