Player name not storing to a variable

-- updated excerpt

local player_id 

game.Players.PlayerAdded:Connect(function(plr)
	player_id = plr.UserId
	workspace:WaitForChild("Current_Player").Value = plr.Name
	print(workspace.Current_Player.Value) -- works
end)

--This will print everytime the value changes
workspace.Current_Player.Changed:Connect(function()
	print(workspace.Current_Player.Value) -- works
end)

task.wait(2)
print(workspace.Current_Player.Value) -- works

Adding a delay could work.

The reason that the print() outside of the functions prints nothing is that it runs before the function that sets the value is called. Setting it outside of any function will just run it emmidiately after you start the game.

1 Like

This is because the print outside of the functions is printing before the functions are even called through the events. When you print this outside of the functions, you’re printing nil because the value has not been assigned to yet. Instead, you should be writing code inside of the functions where the variable has been updated.

1 Like

Thanks guys, the answer has been found though.