Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I make a loop run until an event fires?

Asked by
MuN8MuN 47
5 years ago

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 ;)

2
The loop does stop when moving is set to false. 1waffle1 2908 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago

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)
0
Thanks! :D This worked, but later based on your answer I searched a bit more and found an even better one. MuN8MuN 47 — 5y
Ad

Answer this question