Yielding custom moveTo() function

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.

Maybe you could use polling? where once you have connected the MoveToFinished event you just task.wait() until target reached = true?

EDIT: Dont do polling, just use the solution below.

You could calll humanoid:MoveTo() first, and then use humanoid.MoveToFinished:Wait() instead of :Connect(), which pauses the execution of the script until the event is fired, then whatever happens after that, put it after the event:

local function moveTo()
    humanoid:MoveTo()

    humanoid.MoveToFinished:Wait()

    -- code to run after event fired
end

In my opinion polling is bad practice here, instead we should just let the event to do the job, where Event:Wait() pauses the execution of the script and continues when it is fired.

2 Likes

Does that also pause the place where I call moveTo() function?

Yes, because all of your code are under the same thread, which means if one code executes a yielding function in that thread, that thread is paused.

1 Like

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