How would I tell the script to wait until everyone respawns then open door (for example).
Potential solutions I have are:
Check that all the players are within the radius of spawn (might not be the best, waiting for laggy users)
Collect all the players and LoadCharacteruntested but sounds promising
Just respawn everyone and wait a given time before “opening the door”
I appreciate any help, normally I would try until I fail but I am time limited right now. I did check the forum before posting this, it was a quick check though
A Working Solution:
I have this inside a ModuleScript but you can configure it to whatever you see fit.
-- Edit including information from Forummer's comment
local Players = game:GetService("Players")
Module.RespawnAndWait = function()
for _,plr in pairs(Players:GetChildren()) do
plr:LoadCharacter()
task.wait(1) -- this will cause a wait during the loop
end
task.wait(1) --the wait should go here (if one is necessary) it'll occur after the loop ends
print("All respawned") -- when everyone has respawned...
end
I don’t exactly feel comfortable marking my own answer as the solution, marked it after reading comments.
I think your 2nd option is best. When a player joins, add it in a table. When that player has loaded, store it in a new table for loaded players. Then check that both the waiting and loaded tables are the same. That is how I would go about it, personally.
It was actually quite easy and doesn’t require much.
local Players = game:GetService("Players") -- as Forummer pointed out
Module.RespawnAndWait = function()
for _,plr in pairs(Players:GetChildren()) do
plr:LoadCharacter()
end
-- you can place task.wait(#) here. (After all the players are respawned, wait, then print)
print("All respawned") -- when everyone has respawned...
end
This isn’t exactly what I have (I have sanity checks), this is just the outline draft
local Players = game:GetService("Players")
Module.RespawnAndWait = function()
for _, plr in ipairs(Players:GetPlayers()) do
plr:LoadCharacter()
end
task.wait(1) --the wait should go here (if one is necessary) it'll occur after the loop ends
print("All respawned")
end
Integrating the PlayersService into the local environment allows it to be accessed faster, the ipairs() iterator is typically faster at traversing over the elements of an array as opposed to the pairs() iterator. Finally, the yielding can occur after the loop has completed not after each single iteration/cycle of the loop.
GetPlayers() is faster than GetChildren() as it only looks for player objects.