Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I Loop code for each part in pairs?

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

3 comments

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.

0

You seem to have misunderstood the question. The character is supposed to teleport to each part, not all players to one part.

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.

1 answer

✓ Accepted answer

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.

2 comments

0

Thank you very much.

0

-1 for spoonfeeding

This discussion is preserved as it was. New answers, comments, and votes are closed.