How to Get Local Player

Hello,

I am trying to make a game in which players choose numbers, those numbers which are then stored in values located inside the Local Player. The player presses a button which then should change one of the values.

the following code is run when new players join, adding the values and folder to their player. This part is located in ServerScriptService.

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local WhiteBall1 = Instance.new("IntValue")
	WhiteBall1.Name = "WhiteBall 1"
	WhiteBall1.Parent = leaderstats
	
	local WhiteBall2 = Instance.new("IntValue")
	WhiteBall2.Name = "WhiteBall 2"
	WhiteBall2.Parent = leaderstats
	
	local WhiteBall3 = Instance.new("IntValue")
	WhiteBall3.Name = "WhiteBall 3"
	WhiteBall3.Parent = leaderstats
	
	local WhiteBall4 = Instance.new("IntValue")
	WhiteBall4.Name = "WhiteBall 4"
	WhiteBall4.Parent = leaderstats
	
	local WhiteBall5 = Instance.new("IntValue")
	WhiteBall5.Name = "WhiteBall 5"
	WhiteBall5.Parent = leaderstats
	
	local SuperBall = Instance.new("IntValue")
	SuperBall.Name = "SuperBall"
	SuperBall.Parent = leaderstats
end)

the second script is located in a button which the player presses to change the value: It changes the button’s color to green (that part works) and is supposed to change the value of WhiteBall1, but the script can’t seem to find the LocalPlayer. The output states that WhiteBall1 is not a valid member of Folder and that line 16 doesn’t work


local players = game:GetService("Players")
local plr = players.LocalPlayer

local button = script.Parent

button.BackgroundColor3 = Color3.fromRGB(255,255,255)


function changeWhiteBall1Value()
	
	if button.BackgroundColor3 == Color3.fromRGB(0,255,0) then
		button.BackgroundColor3 = Color3.fromRGB(255,255,255)
		
	elseif button.BackgroundColor3 ~= Color3.fromRGB(0,255,0) then
		button.BackgroundColor3 = Color3.fromRGB(0,255,0)
		plr.leaderstats.WhiteBall1.Value = 1 -- This is Lines 16
	end
	
end

button.MouseButton1Click:Connect(changeWhiteBall1Value)

Thanks for the help.

2 Likes

No I am not, I am actually quite new to scripting (I know basics)

Hello!

Just to make sure. Are you using a LocalScript?
You can’t get the LocalPlayer in normal scripts.

Your script works fine in a localscript.

1 Like

You are getting this error because you aren’t defining WhiteBall1 correctly in your second script because in the leaderstats it has a space in it: WhiteBall 1. Try changing line 16 to this:

plr.leaderstats["WhiteBall 1"].Value = 1 -- This is Lines 16
2 Likes

yes, it is indeed located in a local script,

Here is where it’s located precisely:

Annotation 2020-03-24 132633

Try running your code again. Maybe publish it?

It works fine when i tried it.

What does the output say?

thank you so much for your help ! I was using the same name as the variable in the first code instead of using its actual name…