Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Player is a nil value?

So, I am making a script that when you touch a part, it gives you money. When I try to test it out, it says that players is a nil value.

Here's the code for the part:

script.Parent.Touched:connect(function() player = game:GetService("Players").LocalPlayer stats = players:findFirstChild("leaderstats") points = stats:findFirstChild("Points") points.Value = points.Value + 1 script.Parent:Destroy() print ("Coin completed") end)

Here's the leaderstats script:

game.Players.PlayerAdded:connect(function(player) stats = Instance.new("IntValue") stats.Parent = player stats.Name = "leaderstats" points = Instance.new("IntValue") points.Parent = stats points.Name = "Points" end)

Can someone please help me?

4 comments

0

is it a local script (code in the part)

0

obviously

0

I tried that, didn't work.

0

Research goes a long way. https://developer.roblox.com/api-reference/property/Players/LocalPlayer To quote the Dev Hub, "For Scripts running on the server, this property is nil."

1 answer

✓ Accepted answer

You:

 script.Parent.Touched:connect(function()  
player = game:GetService(“Players”).LocalPlayer  
stats = players:findFirstChild(“leaderstats”)  
points = stats:findFirstChild(“Points”)  
points.Value = points.Value + 1  
script.Parent:Destroy()  
print (“Coin completed”)  
end)

Me:

script.Parent.Touched:Connect(function(p)
	if p:IsA("BasePart") then
		local stats = game.Players:FindFirstChild(p.Parent.Name).leaderstats -- player's stats
		stats.Points.Value = stats.Points.Value + 1
		script.Parent:Destroy()
		print("Coins completed.")
	end
end

as you see, you can't get a player from a normal script unless you use events. ~Enjoy your working code, k bye

1 comment

0

Nailed it

This discussion is preserved as it was. New answers, comments, and votes are closed.