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

Script setting player as nil?

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.

1 comment

0

Change it to a LocalScript, use LocalPlayer, and problem solved.

1 answer

✓ Accepted answer

#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!
--]]

4 comments

0

incapaz Preach it baby

0

Heres the problem, im talking surface gui not screen gui

0

In that case place the SurfaceGui in StarterGui and set the adornee to the part it should be adorned to.

0

OHHH YEAHHHH INCAPAZ THE BEAST!!!!!!

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