So i made this code at the end of my round script, what im trying to achieve is make the players go into the ‘lobby’ team and use :loadcharacter to get them back to spawn.
But what currently happens is that it picks 1 player, then waits and picks another and so forth. which will eventually make my round script loop break. Does anyone know how to fix this (probably) small error?
Please let me know!
local players = game.Players:GetPlayers()
Status.Value = "Removing Assets..."
for i = 1,#players do
if players[i].Character ~= nil then
players[i].Team = Teams["Lobby"]
players[i]:LoadCharacter()
end
ClonedMap:Destroy()
wait(5)
end
end
It is just creating a new thread and executes the code inside it without yielding or pausing the current thread.
You can learn more about this function on its documentation page.
For your case, a task.spawn would allow you to run multiple lines of code at the same time. Like @EgizianoEG stated, I recommend you read the documentation page to know the details.
So, for your script I would do:
local players = game.Players:GetPlayers()
Status.Value = "Removing Assets..."
for i = 1,#players do
if players[i].Character ~= nil then
task.spawn(function() -- task.spawn
players[i].Team = Teams["Lobby"]
players[i]:LoadCharacter()
end)
end
ClonedMap:Destroy()
wait(5)
end
end
It looks like the wait(5) statement is inside the loop, so it will execute after each player is processed. To fix this, you can move the wait(5) statement outside the loop, like this:
Copy code
local players = game.Players:GetPlayers()
Status.Value = "Removing Assets..."
for i = 1,#players do
if players[i].Character ~= nil then
players[i].Team = Teams["Lobby"]
players[i]:LoadCharacter()
end
end
ClonedMap:Destroy()
wait(5)
This will wait for 5 seconds after all players have been processed, rather than waiting after each player.
ive read the documentation on :LoadCharacter() and it says " Note: The function is similar to Player:LoadCharacterBlocking(), but the request is processed asynchronously instead of synchronously. This means other tasks will be able to continue while the character is being loaded, including the rendering of the game and any other tasks."
so it seams that it yielding isnt really an issue.