My script is not working can someone please help

this script is to give player cash when they step on it

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
		game.Players.LocalPlayer.leaderstats.Coins.Value = game.Players.LocalPlayer.leaderstats.Coins.Value + 50
	end
end)

in the output is says

Workspace.Part.Script:4: attempt to index nil with 'leaderstats'

Do you have a leaderstats script? If you dont then it wont work.

yes i do :smiley: :grinning: :smile:

wait nevermind i fixed it :smiley: :smile: :grinning:

Hey, what I would do is this.

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
player.leaderstats.Coins.Value = player.leaderstats.Coins.Value +50
	end
end)

this is from a server script right you can only access local player in a local script thats why you got nil bc localplayer dont exist in server scripts

1 Like

Hello, how are you doing?

Is that a local script or a server script? You’re using local player.

Insert a server script and type this:

local part = script.Parent

part.Touched:Connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if hit.Parent:FindFirstChild("Humanoid") then
        player:WaitForChild("leaderstats").Coins.Value += 50
    end
end)

guys dont give him the code let him figure it out so he can learn

Thats the exact code I wrote above, read before posting.

This should work. Although, game.Players.LocalPlayer will not work in a server script.

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
	     local player = game.Players:GetPlayerFromCharacter(hit.Parent)
         player.leaderstats.Coins.Value += Amount
	end
end
2 Likes

You cannot create a varialbe of a player using game.Players.LocalPlayer because you’re working on a ServerScript, you can do it only on a LocalScript, then why if you create a variable of the player using:
game.Players:GetPlayerFromCharacter(hit.Parent)

you use: game.Players.LocalPlayer

To add to what @iamtkl said (which should work), it might be best to add a debounce, this will allow you to limit the amount of times a player can touch the part in a certain timeframe. An example:

local debounce = false
script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") and not debounce then
         debounce = true
	     local player = game.Players:GetPlayerFromCharacter(hit.Parent)
         player.leaderstats.Coins.Value += Amount
         wait(1)
         debounce = false
	end
end)

What this is doing is preventing you from spamming, it will only let you touch the part every 1 second as the script will only run when debounce is equal to false, as soon as something touches the part, debounce is set to true, it is then set back to false after 1 second.

2 Likes