Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I Loop code for each part in pairs?

Asked by
DBoi941 57
4 years ago

I am trying to move the player to each part in pairs. I am not sure on what to do here. It will move player to the first part in pairs but not the others. Any help would be great.

local player = game.Players.LocalPlayer

for _, v in pairs(game.Workspace.Test:GetChildren()) do
while wait(1) do
        player.Character.HumanoidRootPart.CFrame = v.PrimaryPart.CFrame
    end
end
0
It's because it's a LocalScript. The LocalPlayer only refers to the player associated with the client, not every player in the game. DeceptiveCaster 3761 — 4y
0
You seem to have misunderstood the question. The character is supposed to teleport to each part, not all players to one part. programmerHere 371 — 4y
0
I understand its a locascript I did it that way so I can test. I will change that later. It works but it is just moveing player to the first v over and over and not to the next one. DBoi941 57 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

The while loop is never terminating, thus not allowing for a second+ iteration.

Loops act like "walls" to code under it, but not in it.

Let this be an example:

local i = 0;

while (i < 10) do
    i = i + 1;
end
print("text\nmore text");

The string is printed only after the while loop has terminated.

So the while loop's body will teleport the local player, and the for loop won't iterate a second time because of that loop.

local Workspace, client = game:GetService("Players").LocalPlayer, game:GetService("Workspace");

for _, part in ipairs(Workspace.Test:GetChildren()) do
    client.Character:SetPrimaryPartCFrame(part.CFrame);
    wait(1);
end

If you want to do this forever, then just wrap it in a while loop:

while (true) do
    for _, part in ipairs(Workspace.Test:GetChildren()) do
        client.Character:SetPrimaryPartCFrame(part.CFrame);
        wait(1);
    end
end

Notice that wait is not called in the conditional part of the while loop. Do not do this. This idiom only works because of a hack; a trick. Use true (or some other constant condition), as it is clearer.

0
Thank you very much. DBoi941 57 — 4y
0
-1 for spoonfeeding 0_2k 496 — 4y
Ad

Answer this question