So I’ve seen Child/PlayerAdded events used with a for loop.
Players.PlayerAdded:Connect(function()
--do code
end)
--plr joins here
for _, player in pairs (Players:GetChildren()) do
--do code
end
I have seen this SO much. Is this really necessary? It is also very confusing. What if a player joins in between the event being listened to and the for loop? Wouldn’t that trigger both?
This is important when it comes to things like loading data. If the player joined before the script loaded ( this can occur when the game contains a large amount of objects, instances, parts, etc… ) then the player would have no data, right?
So to counter that problem, you use a for loop below the event listener. As for the “double trigger” problem, I believe it’s unlikely for that to occur. However if you’re worried about that being a problem, you could use attributes to make sure the script only loads in that player once:
local function PlayerAdded(player: Player)
if (player:GetAttribute("Loaded")) then
return
end
player:SetAttribute("Loaded", true)
end
Players.PlayerAdded:Connect(PlayerAdded)
for _, player in pairs (Players:GetChildren()) do
PlayerAdded(player)
end
The chance of that happening is incredibly small. The reason for this coding practice is mainly to account for players joining before the entire script starts running. If you’re worried about that specific case it could probably be mitigated by setting some attribute on the player to indicate whether the startup code has been run on them yet.