While true do seems to break randomly through a for loop

I’m making a UFO that sucks up parts in its tractor beam. Whenever a part of moving, it sucks the part up just fine, but if a part isn’t actively in motion the Touched function doesn’t run. I’m using WorldRoot:GetPartsInPart() to fix this, but it’s not working very well.

function suckup(hit)
	if hit.Anchored == false and hit.Locked == false and hit.Name ~= "UFO" then
		if hit.Parent:FindFirstChild("Humanoid") then
			hit:BreakJoints()
		end
		local bodyvelocity = Instance.new("BodyVelocity")
		bodyvelocity.Parent = hit
		repeat
			bodyvelocity.Velocity = Vector3.new((script.Parent.Position.X - hit.Position.X) * 10, 20, (script.Parent.Position.Z - hit.Position.Z) * 10)
			wait()
		until hit.Parent == nil
	end
end

script.Parent.Touched:Connect(suckup)

while wait() do
	script.Parent.Position = Vector3.new(script.Parent.Parent.UFO.Position.X, 14, script.Parent.Parent.UFO.Position.Z)
	local parts = workspace:GetPartsInPart(script.Parent)
	if #parts > 0 then
		for i, part in pairs(parts) do
			suckup(part)
		end
	end
end

Based on my testing, while true do part of the script runs once and then breaks randomly. Do for loops not work inside of while loops?

1 Like

I believe this part may be the issue

repeat
	bodyvelocity.Velocity = Vector3.new((script.Parent.Position.X - hit.Position.X) * 10, 20, (script.Parent.Position.Z - hit.Position.Z) * 10)
	wait()
until hit.Parent == nil

Regardless put a print into each loop to debug by tracing the program

2 Likes

Thank you, I see now. What should I do about that, though? How do you spawn() with arguments?

I discovered I probably should use coroutine.wrap(), but it still didn’t work so I gave up. Thanks, though.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.