Help with coin script

Hey Devs,

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)

Thanks for reading!

3 Likes

GetPlayerFromCharacter needs the character as input, and not the humanoid. Try writing humanoid.Parent instead.

2 Likes

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.

3 Likes

What part of the script do I change?

1 Like

change line 7 to

local player = players:GetPlayerFromCharacter(humanoid.Parent)
2 Likes

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.

yeah honestly, it would work better with
game.Players:GetPlayerFromCharacter(char)

the script cant detect if a player touches it correct?

try print debugging
add a print statement after every line of code
and see where it stops

wdym? this isnt my problem
\\\\\\

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)

I hope that was helpful and have a nice day !