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

How to wait for a for loop to end complete before completing next task?

I am trying to make a model hover in place a little bit by using SetPrimaryPartCFrame. I tried using for loops and while loops in order to make it go up the proper amount and down the same amount but I quickly realized that it would glitch out since it would execute both loops at the same time. I tried to do this as a fix since I wasn't sure how to check if the position of the part's CFrame was returned to its original spot:

local model = script.Parent
local up = true

while true do
	if up == true then
		for i = 1,2, .1 do
			model:SetPrimaryPartCFrame(model:GetPrimaryPartCFrame() * CFrame.new(0, 0 + i, 0))
			wait()
			print(i)
		end
		up = false
	end
	if up == false then
		for i = 2, 1, -.1 do
			model:SetPrimaryPartCFrame(model:GetPrimaryPartCFrame() * CFrame.new(0, 0 - i, 0))
			wait()
			print(i)
		end
		up = true 
	end
end

I used the variable up as a way to check if its moving up or not and it seemed to work for a little while but after a few seconds one of the loops began to take over and the object slowly kept going lower and lower towards the ground rather than going up and down the same amount to give a hovering effect. I was just wondering if there is an easier fix for this.

Thanks in advanced, any help is appreciated.

2 comments

0

It already does that...?

0

Not quite, the model moves lower and lower after a couple of seconds of running the script.

1 answer

✓ Accepted answer

The math in the second for-loop accumulates differently than the first. It's hard to see but particularly starting with 2 is a problem because it allows 2 to be added, but the first loop does not allow 2 to be added. So, it adds more.

Heres a version using equivalent loops. and I recommend TranslateBy, this is a good use.

local model = script.Parent

while true do
   for i = 1,2,.1 do
        model:TranslateBy(Vector3.new(0, i, 0))
        wait()
   end
   for i = 1,2,.1 do
      model:TranslateBy(Vector3.new(0, -i, 0))
      wait()
   end
end

cheers

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