I’m fairly new to coding on Roblox so I’m probably doing something stupid, but anyways everything other than the PlayerAdded function seems to run–its a normal script in StarterGui
--Makes a variable that will hold the PlayerGui
local PlayerGui = nil
print("hello") --this works
--Makes sure the player is added so that the PlayerGui can be accessed
game.Players.PlayerAdded:Connect(function(player)
print("hello") --this doesn't work :/
PlayerGui = player.PlayerGui
end)
print("hello") --this works
--Makes a ScreenGui inside of PlayerGui
local ScreenGui = Instance.new("ScreenGui")
ScreenGui.Parent = PlayerGui
ScreenGui.Name = "ScreenGui"
--Makes a TextButton inside of ScreenGui
local TextButton = Instance.new("TextButton")
TextButton.Parent = ScreenGui
TextButton.Name = "TextButton"
It does this in Studio because sometimes the player can load faster than your script. To fix it, just call the function on all of the players that are already loaded in.
--Makes a variable that will hold the PlayerGui
local PlayerGui = nil
print("hello") --this works
--Makes sure the player is added so that the PlayerGui can be accessed
local function playerAdded(player)
print("hello")
PlayerGui = player.PlayerGui
end)
game.Players.PlayerAdded:Connect(playerAdded)
for _, v in game.Players:GetPlayers() do
playerAdded(v)
end
print("hello") --this works
--Makes a ScreenGui inside of PlayerGui
local ScreenGui = Instance.new("ScreenGui")
ScreenGui.Parent = PlayerGui
ScreenGui.Name = "ScreenGui"
--Makes a TextButton inside of ScreenGui
local TextButton = Instance.new("TextButton")
TextButton.Parent = ScreenGui
TextButton.Name = "TextButton"
It does this in a live session too, a player’s containers and character can only be added once the player has been added. Local scripts will only run in containers of the player or its character.
What does this do exactly? I’m gonna assume its something like a for loop that checks which players are already loaded in or something but idk. I’m not someone who’s gonna copy and paste this into a game without understanding
Correct, that iterates over each player instance that is currently in the game and passes it to the callback function that handles the PlayerAdded event/signal.
local Game = game
local Players = Game:GetService("Players")
local function OnPlayerAdded(Player)
print(Player.Name)
end
Players.PlayerAdded:Connect(OnPlayerAdded) --Will account for all new players which visit the game.
for _, Player in ipairs(Players:GetPlayers()) do
OnPlayerAdded(Player) --Will account for all current players that are already in the game.
end