How do I wait for 1 of multiple events to fire

So I am currently using SimplePath to do some pathfinding. I am running the path, waiting for the npc to make it to the end of the path, and then restarting with a new location. I am using Path.Reached:Wait() in order to wait for the npc to make it to the end of the path before pathing to a new position. However, sometimes there is an error that happens when it fails to compute the path. When this happens it fires the Path.Error event and never fires the Path.Reached event meaning there is an infinite yield. How would I be able to yield the script until either one of those fire?

You could put the code that needs to fire after the yield inside of a function, then fire the function using :Connect, such that iether event fires it:

local function DoStuff()

end

Path.Reached:Connect(DoStuff)
Path.Error:Connect(DoStuff)

If you’re concerned about memory usage, you can also store the connections in a table, then loop through the table and disconnect each connection when the function is called.

A single scope can only yield for 1 signal:Wait(). A complex approach to do what you’re trying to do would be to use coroutine.yield() then call coroutine.resume() inside of both the Error and Reached signal, so that whatever happens to fire first would be the one resuming the coroutine.

Coroutines are annoying and almost entirely useless, so a better way of doing it would be to shuffle your logic around so it’s not blocking to wait to restart or advance. Would need to see code to know how to apply it for your scenario but it’s along the lines of calling an advanceStep() function inside of Reached:Connect() instead of a blocking loop pattern.

Assuming you have something like this.

for _, waypoint in path:Get() do
   path.Reached:Wait()
end

So you’d be looking to format it more like

local path, currentWaypoint =  nil, 0

local function nextWaypoint()
    currentWaypoint += 1
    humanoid:MoveTo(path[currentWaypoint])
end

local startWalking

startWalking = function() -- let us call our function from inside our function
-- computes a new path then restarts waypoint index back to 1
   path = whatever:ComputeAsync()

   path.Reached:Connect(nextWaypoint)
   path.Error:Connect(startWalking)
end

startWalking()

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