My Loop Doesn't Loop Through Players

Recently, I was trying to loop through the players to teleport them, but somehow, the loop doesn’t work.

I made sure that the function called by printing “Called”

local players = game.Players:GetPlayers()

local function teleportToMap(Spwans)
print("Called")

for i,plr in pairs(players) do
    if plr.Character then
        if plr.Character:FindFirstChild("HumanoidRootPart") then
            plr.Character.HumanoidRootPart.CFrame = Spwans[math.random(1,#Spwans)].CFrame

               end
           end
       end
 end

teleportToMap(workspace.Map:WaitForChild("Spawns"):GetChildren())

When setting the variable ‘players’, you’re not setting the function, but the return of ‘GetPlayers’ to that variable. This means that no matter how many times ‘players’ is referenced, the value will never change as it’s already been set.

Instead, try this:

local players = game:GetService('Players')

local function teleportToMap(Spwans)
print("Called")

for i,plr in pairs(players:GetPlayers()) do
    if plr.Character then
        if plr.Character:FindFirstChild("HumanoidRootPart") then
            plr.Character.HumanoidRootPart.CFrame = Spwans[math.random(1,#Spwans)].CFrame

               end
           end
       end
 end

teleportToMap(workspace.Map:WaitForChild("Spawns"):GetChildren())
1 Like

I got it. Thank you, really appreciate it. :slightly_smiling_face: