Need Help Fixing a Index nil Problem

So I scripted code that would give the player money once they collect it. I noticed however if you were to hold a tool and it would come in contact with the coin, it would still give the player the money but it would return [Workspace.Coins.Coin.Script:4: attempt to index nil with ‘leaderstats’]. I think it has something to do with the tool touching the coin instead of the player first. Any ideas how to make it where the script only checks if the player touched it. Same problem with a door script I have.

script.Parent.Touched:Connect(function(hit)
	local player = hit.Parent:FindFirstChild("Humanoid")
	local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
	if plr.leaderstats.Cash.Value >= 0 then
		wait()
		script.Disabled = true
		script.Parent.Transparency = 1
		script.Parent.CanCollide = false
		plr.leaderstats.Cash.Value = plr.leaderstats.Cash.Value +1
		wait(1)
		script.Parent.Transparency = 0
		script.Parent.CanCollide = true
		script.Disabled = false
	end
end)

You need to check if the player actually exists.

script.Parent.Touched:Connect(function(hit)
	local player = hit.Parent:FindFirstChild("Humanoid")
    if not player then return end -- This line should fix it.
	local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
	if plr.leaderstats.Cash.Value >= 0 then
		wait()
		script.Disabled = true
		script.Parent.Transparency = 1
		script.Parent.CanCollide = false
		plr.leaderstats.Cash.Value = plr.leaderstats.Cash.Value +1
		wait(1)
		script.Parent.Transparency = 0
		script.Parent.CanCollide = true
		script.Disabled = false
	end
end)
1 Like