Hello I’m making a game where NPC’s should move to a certain location. I use a function for this which I can call everywhere in the script. Here is my code:
local function moveTo(humanoid, targetPoint, andThen) -- andthen must be a function
local targetReached = false
local connection
connection = humanoid.MoveToFinished:Connect(function(reached)
print(reached)
targetReached = true
connection:Disconnect()
connection = nil
if andThen then
andThen()
end
end)
humanoid:MoveTo(targetPoint)
while not targetReached do
if not (humanoid and humanoid.Parent) then
break
end
-- Has the target changed?
if humanoid.WalkToPoint ~= targetPoint then
break
end
-- refresh the timeout
humanoid:MoveTo(targetPoint)
task.wait(6)
end
-- disconnect the connection if it is still connected
if connection then
connection:Disconnect()
connection = nil
end
end
local function andThen()
-- do stuff
end)
moveTo(humanoid, Vector3.new(2,2,2), andThen)
print("reached")
My question is how can I let moveTo() yield so I dont have to use a andThen() function. My desired outcome is that “reached” is printed after the moveTo function has finished.