01 | function click() |
02 | local stick = script.Parent |
03 | local Player = game.Players.LocalPlayer |
04 | repeat wait(. 01 ) until Player:FindFirstChild( "PlayerGui" ) |
05 | wait(. 1 ) |
06 | stick.Transparency = 1 |
07 | stick.CanCollide = false |
08 | stick.ClickDetector.MaxActivationDistance = 0 |
09 |
10 | local num = Player.PlayerGui.ScreenGui.Frame.rockSec.num.Text |
11 | Player.PlayerGui.ScreenGui.Frame.rockSec.num.Text = num + 1 |
12 |
13 |
14 | end |
15 |
16 | 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.
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.