MoveToFinished doesnt work - pathfinding

everythings seems to work except of the movetofinished part. When i put the breakpoint before the function it just skips to the last end keyword. Why is this happening?

local Enemy = {}
Enemy.__index = Enemy
local ServerStorage = game:GetService("ServerStorage")
local Pathfinding = game:GetService("PathfindingService")

local connection



function Enemy:Movement(targetPosition)
	local RETRY_NUM = 0
	local success,errorMsg
	repeat
		RETRY_NUM += 1
		success,errorMsg = pcall(self.Path.ComputeAsync,self.Path,self.HRP.Position,targetPosition)
		if errorMsg then
			warn("PathfindingError"..errorMsg)
			task.wait(5)
		end
	until success == true or RETRY_NUM > 20
	if success then
		if self.Path.Status == Enum.PathStatus.Success then
			local waypoints = self.Path:GetWaypoints()
			local currentWaypoint = 2
			
			if not connection then
				connection = self.Humanoid.MoveToFinished:Connect(function(reached)
					if reached and currentWaypoint < #waypoints then
						currentWaypoint += 1
					
						self.Humanoid:MoveTo(waypoints[currentWaypoint].Position)
					else
						connection:Disconnect()
						connection = nil
					end
				end)
			end
		else
			return
		end
	else
		warn("PATHFIND ERROR: "..errorMsg)
	end
end

function Enemy.New(pos,Name)
	local Enemy1 = {}
	Enemy1.Model = ServerStorage.Enemies[Name]:Clone()
	Enemy1.Model.Parent = workspace
	Enemy1.Model:SetPrimaryPartCFrame(CFrame.new(pos))
	Enemy1.HRP =  Enemy1.Model:WaitForChild("HumanoidRootPart")
	Enemy1.Humanoid = Enemy1.Model:WaitForChild("Humanoid")
	Enemy1.Path = Pathfinding:CreatePath()
	Enemy1.ReachedConnection = false
	setmetatable(Enemy1,Enemy)
	return Enemy1
end


return Enemy

2 Likes

I suppose it depends on what you mean by that part not working
the line
connection = self.Humanoid.MoveToFinished:Connect(function(reached)
… subsequent code

does not actually execute that function, it connects that function to be what executes when the MoveToFinished event happens sometime later. putting a breakpoint before here and single stepping this line will only assign an RBXScriptSignal to the variable connection, so it moved right past it to end. But that’s fine/expected based on what you’re doing here. The function will not execute until the Humanoid has finished it’s moving, and I assume this is what you want

Was there another reason this script doesn’t work?

1 Like

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