My teleportation script is very inconsistent, what should i do?

So basically, I made a button that teleports players into the game when pressed. However, it is very incosistent. Sometimes, it will teleport only the person who clicks the button. Sometimes, it will teleport only the other players who didn’t press the button, and so forth. Here is the code which is in a serverscript:
local list = {}

local id = 9405917336

local TeleportService = game:GetService(“TeleportService”)

game.ReplicatedStorage.RemoteEvent.OnServerEvent:Connect(function()

TeleportService:TeleportPartyAsync(id, list)

end)

game.Players.PlayerAdded:Connect(function(plr)

table.insert(list, plr)

end)

have u tried looping through the whole table and teleporting every single one with the loop

No, I have not. Could you give me an example of what you mean?

Looks like your issue might be that you’re not getting players already in the game by the time this script starts. It is some inconsistent behavior that Roblox has, but basically, whenever you want a function to run for all players, you also have to loop through the players from before that connection is made to new players.

Example code:

local function PlayerAdded(Player)
   table.insert(list,Player)
end

game.Players.PlayerAdded:Connect(PlayerAdded)
for _,Player in ipairs(game.Players:GetPlayers()) do
   task.defer(PlayerAdded,Player) -- Defer to preserve threaded behavior of the connection
end

Thanks! I’ll try it out tomorrow when I wake up :grinning:

Thanks so much! It worked! It must have been the task.defer thing!

It was not, but running the PlayerAdded function for pre-existing players is really important, since sometimes Scripts load in after players/ load in before the assets they want to use.