Why does my code only run when a wait() is added?

So I was coding a simple for loop that goes through Players and prints out the players. anyway I noticed that my code will run correctly and print out the players name with the wait statement. I have been wondering why this occurs. Is it because the script runs before the game itself has properly loaded or am I missing something important which needs to be done?

my code is below

local door = script.Parent
wait(2)
local players = game:GetService("Players")
local players_get = players:GetPlayers()


for i, v in pairs(players_get) do
	print(v)
end

As previously mentioned, if I remove the wait nothing is printed to the output console, however if I do wait then it correctly prints out my username which I expect it to do.

Could someone please shed some light as to why this is?

The game itself will be loaded, but the script will run before any players enter the game

This is where events like Players.PlayerAdded come into play

Players.PlayerAdded:Connect(function(player)
    print(player)
end)
1 Like

Oh, this makes sense now thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.