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

Script setting player as nil?

Asked by 5 years ago

My script is a normal script who's purpose is to set the text of a TextLabel to the value of a NumberValue which is inside the player. Heres the script:

--Get player variables.
local Players = game:GetService("Players")
local Player = Players:FindFirstChildOfClass("Player")
local Coins = Player.PlayerGui.Coins

--Get gui variables.
local CoinDisplay = script.Parent.Stats.Coins.CoinsDisplay

--Set functions.
local function SetCoins()
    CoinDisplay.Text = Coins.Value
end

--Connect functions.
Coins.Changed:connect(SetCoins)

For some reason it always says that the player is a nil value. I've tried doing: local Player = Players.LocalPlayer But it made the same error.

0
Change it to a LocalScript, use LocalPlayer, and problem solved. User#19524 175 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

Ancestry

The top ancestor (excluding the DataModel and the Players service) of a LocalScript is, well, the LocalPlayer. Scripts run on the server, whilst LocalScripts run on the client.

Why LocalPlayer is nil on the server

Think of it as your school classroom. Your desk is your desk, just like how your LocalScript is your LocalScript, it works for you. But your classroom is your classroom, and in it are your classmates as well as your teacher. Think of the classroom as the server. It has everyone in it, and if your game has multiple players in it, it can't randomly choose who LocalPlayer is! For this reason, LocalPlayer is nil on the server. Code cannot your mind. This is why it must be all typed out. So instead of doing this:

make a part inside of the workspace with color red

You must do this:

local part = Instance.new("Part")
part.BrickColor = BrickColor.new("Really red")
part.Parent = workspace 

The solution to your problem would be to simply use a LocalScript, as Scripts do not run in PlayerGui. They run in PlayerGui from Play Solo, and ran when Experimental Mode existed, but with that mode gone this is no longer the case in a server.

--Get player variables.
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Coins = Player.PlayerGui.Coins

--Get gui variables.
local CoinDisplay = script.Parent.Stats.Coins.CoinsDisplay

--Set functions.
local function SetCoins()
    CoinDisplay.Text = tostring(Coins.Value)
end

--Connect functions.
Coins.Changed:Connect(SetCoins)
--Connect should be used as connect is deprecated.

--[[
    Remember to use a LocalScript!
--]]
0
incapaz Preach it baby hboogy101 0 — 5y
0
Heres the problem, im talking surface gui not screen gui 20002000sa 83 — 5y
0
In that case place the SurfaceGui in StarterGui and set the adornee to the part it should be adorned to. User#19524 175 — 5y
0
OHHH YEAHHHH INCAPAZ THE BEAST!!!!!! greatneil80 2647 — 5y
Ad

Answer this question