Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 6 years ago
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.

0
ugh is this in a localscript...? radusavin366 617 — 6y
0
It's not, will that fix everything? I thought local scripts wouldn't let me change transparency and such. devisings 58 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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.

0
Please refrain from copying me. User#19524 175 — 6y
Ad

Answer this question