Players teleporting to the same spot? Server-sided Script

Does anybody know the causes/symptoms of this and what might be happening? I’m still a fairly new programmer (just started maybe two or three weeks ago) and am still inexperienced.

I have a script on the Server side basically teleporting players from the lobby into the game area. In the game area there’s random spots where they can teleport to, however, they’re all getting teleported into the same spot.

Here’s an example of what I’m doing:

randomSeat = table.remove(seatArray, math.random(#seatArray));
for i, players in ipairs(game.Teams.Spectators.GetPlayers()) do
    if players.Character and players.Character:FindFirstChild("HumanoidRootPart") then
        players.Character.HumanoidRootPart.CFrame = randomSeat.Seat.CFrame;
    end
end

I’m also not sure if it’s because I put it in a function like this either:

players.PlayerAdded:Connect(function(player)

The randomSeat variable is on the outside of the for-loop encasing the for-loop for the second set of code (if that makes any sense). Example:

for i, players in ipairs(game.Teams.Spectators:GetPlayers()) do
    randomSeat  = table.remove(seatArray, math.random(#seatArray));
...
...
    for i, players in ipairs(game.Teams.Spectators.GetPlayers()) do
        if players.Character and players.Character:FindFirstChild("HumanoidRootPart") then
            players.Character.HumanoidRootPart.CFrame = randomSeat.Seat.CFrame;
        end
    end
...
...
end

The problem is that you decide the teleport spot before you teleport your players. In other words, you initialized a variable and are now using that same value over and over again. If you were to print(#seatarray) just before the second for-loop and just after that same for-loop, you’d notice that the length of the array is the same.

Try moving the randomSeat variable into that second for-loop, within the if statement and you’ll definitely have some luck.

Edit: I made a quick graphic for anybody that might be interested. In the first image,
https://gyazo.com/8712cfd88214f22d44d5b615dbb023c5
you’ll notice we continuously iterate through a loop with the seat variable, an unchanging value (we have no power to change this once we’ve entered the loop, unless we call for seat again within the loop). In the second image,
https://gyazo.com/2dce3d55895b9cc450066c13be95035a
you’ll notice we will iterate through the loop, but we have the power to change the value of seat (if we so desire).

1 Like

I wish I could be as good as this forum at finding little things like this. T_T

Edit: Thank you for the follow-up with the graphics. I understand it clearly now!