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

Why will my while wait() loop inside a function only run once?

game.Players.PlayerAdded:Connect(function(player)

while wait() do

local char = player.CharacterAdded:wait()

local hum = char:WaitForChild("Humanoid")

local pastpos = char:WaitForChild("HumanoidRootPart").Position

wait(0.1)

local newpos = char:WaitForChild("HumanoidRootPart").Position

local mag = (newpos-pastpos).magnitude

print(mag)

end

end)

I get no errors and mag is only printed once.

1 answer

✓ Accepted answer

You're waiting for the CharacterAdded event to fire at the beginning of every loop, which yields until a new character is added. You should define the variable outside of the loop - perhaps handle the magnitude shenanigans inside a listener of the event itself?

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