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

How do I fix the error: "attempt to index local 'Player' (a nil value)"?

function click()
	local stick = script.Parent
	local Player = game.Players.LocalPlayer
	repeat wait(.01) until Player:FindFirstChild("PlayerGui")
	wait(.1)
	stick.Transparency = 1
	stick.CanCollide = false
	stick.ClickDetector.MaxActivationDistance = 0
	
	local num = Player.PlayerGui.ScreenGui.Frame.rockSec.num.Text
	Player.PlayerGui.ScreenGui.Frame.rockSec.num.Text = num + 1
	
	
end

script.Parent.ClickDetector.MouseClick:connect(click)

I have a rock and I when I click the rock I want it to add 1 to the 'PlayerGui.ScreenGui.Frame.rockSec.num.Text'. When I run this in studio it works fine. When I run it in an actual game I get the error like:

"Workspace.Rock.rockClicked:6: attempt to index local 'Player' (a nil value)"

I'm confused about how to fix this because it works fine in Roblox Studio.

2 comments

0

ugh is this in a localscript...?

0

It's not, will that fix everything? I thought local scripts wouldn't let me change transparency and such.

1 answer

✓ Accepted answer

This works in Roblox Studio because in Roblox Studio, you are the server and the client. (Your computer runs the game and plays the game) However, while playing through Roblox itself, you are just the client.

This code runs in a Script, not a LocalScript, so this code will be run on the server. Only the client has access to game.Players.LocalPlayer, since the Roblox game server does not actually have a player. That's why this only errors in a roblox game and not Studio.

Luckily, ClickDetector's MouseClick event also passes a player object with it, so you know who clicked it. http://robloxdev.com/api-reference/event/ClickDetector/MouseClick

You can use that instead of game.Players.LocalPlayer to fix the error.

Hopefully that clears things up.

1 comment

0

Please refrain from copying me.

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