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 make a loop run until an event fires?

Hi! :D How do I make a loop run until an event fires? In my case I need the loop on line 13 to run until the BPos.ReachedTarget event fires, in human words, I need the Body gyro to rotate at the part until the Body position reached the target. The script I made doesn't stop the loop. Any suggestions?

local RunService = game:GetService('RunService')
local p = workspace.p2
local init = p.CFrame
local BPos = p.BodyPosition
local BGyro = p.BGyro

local moving = true

BPos.Position = workspace.p1.Position
BPos.ReachedTarget:Connect(function()
	print('a')  -- For checking
	moving = false
end)
while moving do
	lookAt = CFrame.new(p.Position, workspace.p1.Position)
	BGyro.CFrame = lookAt
	RunService.Heartbeat:Wait()
end

Thanks in advance ;)

1 comment

2

The loop does stop when moving is set to false.

1 answer

✓ Accepted answer

You can use 'Stepped' in RunService to detect if moving is false or true

But this should work:

local RunService = game:GetService('RunService')
local p = workspace.p2
local init = p.CFrame
local BPos = p.BodyPosition
local BGyro = p.BGyro

local moving = true

RunService.Stepped:Connect(function()
	if moving then -- Is true
    	lookAt = CFrame.new(p.Position, workspace.p1.Position)
    	BGyro.CFrame = lookAt
	end
end)

BPos.Position = workspace.p1.Position
BPos.ReachedTarget:Connect(function()
    print('a')  -- For checking
    moving = false
end)

1 comment

0

Thanks! :D This worked, but later based on your answer I searched a bit more and found an even better one.

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