Coin Collect Script

The coin isn’t letting me pick it up.

Code:

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local leaderstats = player:WaitForChild("leaderstats")
local Coin = game.Workspace.AssetsAndModels.Coin

Coin.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
	  	leaderstats.Coins.Value += 1
	end
end)

Error:

All help appreciated!:smile:

2 Likes

Are you sure there is a value in the leaderstats folder by the name “Coins”?

1 Like

Yes I added it in in the DataStore Script

1 Like

I don’t know but couldn’t you just put the player and leaderstats inside the function itself so it finds the values whenever someone touches the part?

1 Like

For testing, might not be a solution but they maybe you can find some other extra info about the error

1 Like

I got an error:

1 Like

So the player is nil. Is this a local script or server sided script?

1 Like

A script inside of the Coin itself

1 Like

Oh okay, then something like this should work.

local Players = game:GetService("Players")
local Coin = game.Workspace.AssetsAndModels.Coin

local db = false

Coin.Touched:Connect(function(hit)
	if db == true then return end
	db = true
	if Players:FindFirstChild(hit.Parent.Name) then
	    local player = Players:FindFirstChild(hit.Parent.Name)
	    local leaderstats = player:FindFirstChild("leaderstats")
	    leaderstats.Coins.Value += 1
	end
	wait(.2)
	db = false
end)

I added the db just so it doesn’t add the coin multiple times.

1 Like
local Players = game:GetService("Players")
local Coin = workspace.AssetsAndModels.Coin

local Debounce = false

Coin.Touched:Connect(function(Hit)
	if Debounce then
		return
	end
	Debounce = true
	
	local HitModel = Hit:FindFirstAncestorOfClass("Model")
	if HitModel then
		local HitPlayer = Players:GetPlayerFromCharacter(HitModel)
		if HitPlayer then
			HitPlayer.leaderstats.Coins.Value += 1
		end
	end
	task.wait(0.5)
	Debounce = false
end)

Previous code looked a little messy. This version will also count touches which occur due to the player’s character’s accessories.

Local player is nil on server but its not on the client ,so if your script is normal this is the error

LocalPlayer is nil on server yes. If you want to do this through the client it won’t be nil

1 Like