MoveTo() breaks script (needs to be fixed)

basically, i have a script where an NPC pathfinds to random waypoints but if a player is near it, itll pathfind to the player instead.

However, when it tries to pathfind to the player, it is also trying to pathfind to the waypoint which causes it to not move.
CODE:

--Services--
local RunService = game:GetService('RunService')
local PathfindingService = game:GetService('PathfindingService')

--Variable--
local hum = script.Parent.Humanoid
local humrp = script.Parent.HumanoidRootPart
local Animator = hum.Animator


--Pathfinding
script.Parent.PrimaryPart:SetNetworkOwner(nil)
local destination1 = workspace.waypoint1.Position

local function findTarget()
	local players = game.Players:GetPlayers()
	local MaxDistance = 50
	local nearestTarget
	
	for i,v in pairs(players) do
		if (v.Character) then
			local target = v.Character
			local distance = (humrp.Position - target.HumanoidRootPart.Position).Magnitude
			
			if (distance < MaxDistance) then
				nearestTarget = target
				MaxDistance = distance
			end
		end
	end
	
	return nearestTarget
end

local function agro(target)
	local distance = (humrp.Position - target.HumanoidRootPart.Position).Magnitude
		local path = PathfindingService:CreatePath()
		path:ComputeAsync(humrp.Position, target.HumanoidRootPart.Position)
		local waypoints = path:GetWaypoints()
	if (distance > 8) then
		for i,v in pairs(waypoints) do
		hum:MoveTo(v.Position)
		
		hum.MoveToFinished:Wait()
		end
	else
		
		target.Humanoid.Health = 0
	end
end

local function createPath(destination)
	local path = PathfindingService:CreatePath()
	path:ComputeAsync(humrp.Position, destination)
	
	return path
end

local function walkTo(destination)
	local path = createPath(destination)
	
	local waypoints = path:GetWaypoints()

	for i,v in pairs(waypoints) do
		local target = findTarget()
		
		if (target) then
			agro(target)
			break
		end
		
		hum:MoveTo(v.Position)

		hum.MoveToFinished:Wait()
	end
end

RunService.Heartbeat:Connect(function()
	walkTo(destination1)
end)
``
local serv = game:GetService("PathfindingService")
local human = script.Parent:WaitForChild("Humanoid")
local body = script.Parent:FindFirstChild("Torso") or script.Parent:FindFirstChild("HumanoidRootPart")
local dest = workspace:FindFirstChild("Spot Name")
local path = serv:CreatePath()
path:ComputeAsync(body.Position,dest.Position)
if path.Status == Enum.PathStatus.Success then
    local wayPoints = path:GetWaypoints()
    for i = 1,#wayPoints do
        local point = wayPoints[i]
        human:MoveTo(point.Position)
        local success = human.MoveToFinished:Wait()
        if point.Action == Enum.PathWaypointAction.Jump then
            human.WalkSpeed = Speed Choices
            wait(0.2)
            human.WalkSpeed = Speed Choices
            human.Jump = true
        end
        if not success then
            print("trying again")
            human.Jump = true
            human:MoveTo(point.Position)
            if not human.MoveToFinished:Wait() then
                break
            end
        end
    end
end

i want to use my own script, how could i solve the problem though?

I think you either typed something wrong or forgot to put a destination

what are you moving? players/npc/model? because if player you should use CFrame [my opinion]

example:

game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new( -- your position )

nevermind i see you’re moving a character
why are you trying to move the humanoid?

so they can move to the waypoint/character?? obviously

what do you mean? thats not even the problem, the problem is 2 MoveTo are playing at the same time when 1 should override the other

Can’t you just use a debounce for that? Once the path ends set it to false so a new path can be created without overriding the other

1 Like

how should i put it in the script? can you give me an example?

same problem, nothing changed. the npc is still stuck on going to both the move to

-- Lua Fixer / WhutThe#4005 
local RunService = game:GetService('RunService')
local PathfindingService = game:GetService('PathfindingService')
local hum = script.Parent.Humanoid
local humrp = script.Parent.HumanoidRootPart
local Animator = hum.Animator
script.Parent.PrimaryPart:SetNetworkOwner(nil)
local destination1 = workspace.waypoint1.Position
local findTarget = function()
    local players = game:GetService("Players"):GetPlayers()
    local MaxDistance = 50
    local nearestTarget
    for i, v in pairs(players) do
        if (v.Character) then
            local target = v.Character
            local distance = (humrp.Position - target.HumanoidRootPart.Position).Magnitude
            if (distance < MaxDistance) then
                local nearestTarget = target
                MaxDistance = distance
            end
        end
    end
    return nearestTarget
end
local agro = function(target)
    while ((humrp.Position - target.HumanoidRootPart.Position).Magnitude > 8) do
        local path = PathfindingService:CreatePath()
        path:ComputeAsync(humrp.Position, target.HumanoidRootPart.Position)
        local waypoints = path:GetWaypoints()
        for i, v in pairs(waypoints) do
            hum:MoveTo(v.Position)
            hum.MoveToFinished:Wait()
        end
        task.wait()
    end
    target.Humanoid.Health = 0
end
local createPath = function(destination)
    local path = PathfindingService:CreatePath()
    path:ComputeAsync(humrp.Position, destination)
    return path
end
local walkTo = function(destination)
    path = createPath(destination)
    local waypoints = path:GetWaypoints()
    for i, v in pairs(waypoints) do
        local target = findTarget()
        if (target) then
            agro(target)
        end
        hum:MoveTo(v.Position)
        hum.MoveToFinished:Wait()
    end
    
end
while true do
    walkTo(destination1)
end

Please try this one!

it only moves to the part, nothing happens when its near the player

I had a similar problem to this, all I did to fix it I’m pretty sure was add another variable called foundtarget which would equal nil, in the walk to destination function I have it check if foundtarget is equal to 1, and if so it breaks the path to the destination, then fires the find path to target.
Code to follow and target script

local pathfindingService = game:GetService("PathfindingService")
local foundtarget = nil
local targetpos = nil

local humanoid = script.Parent.Humanoid
local humanoidrootpart = script.Parent.HumanoidRootPart
local body = script.Parent:FindFirstChild("Torso")
local destination = game.Workspace.PizzaMen.PizzaMan1PatrolBlocks
body:SetNetworkOwner(nil)
local points = {
	destination["1"],
	destination["2"],
	destination["3"],
	destination["4"],
	destination["5"],
	destination["6"],
	destination["7"],
	destination["8"],
	destination["9"],
	destination["10"],
	destination["11"],
	destination["12"],
	destination["13"],
}

foundtarget = nil

function walkRandomly()
	local point = points[math.random(1,#points)]
	local target = FindTarget()
	local path = game:GetService("PathfindingService"):CreatePath()
	path:ComputeAsync(humanoidrootpart.Position, point.Position)
	local waypoints = path:GetWaypoints()
	for _, waypoint in ipairs(waypoints) do
		humanoid:MoveTo(waypoint.Position)
		if foundtarget == 1 then break end
		humanoid.MoveToFinished:Wait()
		FindTarget()
	end
end

function findPath(target)
	local path = game:GetService("PathfindingService"):CreatePath()
	path:ComputeAsync(humanoidrootpart.Position,target.Position)
	local waypoints = path:GetWaypoints()

		for _, waypoint in ipairs(waypoints) do
			humanoid:MoveTo(waypoint.Position)
			if checkSight(target) == true then
				repeat
					humanoid:MoveTo(target.Position)
					wait()
					if target == nil then
						break
					elseif target.Parent == nil then
						break
					end
			until checkSight(target) == false
			foundtarget = nil
				break
			end
			if (humanoidrootpart.Position - waypoints[1].Position).magnitude > 30 then
				findPath(target)
				break
			end
		end
	end

function FindTarget()
	local dist = 35
	local target = nil
	local potentialTargets = {}
	local seeTargets = {}
	for i,v in ipairs(workspace:GetChildren()) do
		local human = v:FindFirstChild("Humanoid")
		local torso = v:FindFirstChild("Torso") or v:FindFirstChild("HumanoidRootPart")
		if human and torso and v.Name ~= script.Parent.Name then
			if (humanoidrootpart.Position - torso.Position).magnitude < dist and human.Health > 0 then
				table.insert(potentialTargets,torso)
			end
		end
	end
	if #potentialTargets > 0 then
		for i,v in ipairs(potentialTargets) do
			if checkSight(v) then	
				table.insert(seeTargets, v)
			elseif #seeTargets == 0 and (humanoidrootpart.Position - v.Position).magnitude < dist then
				target = v 
				dist = (humanoidrootpart.Position - v.Position).magnitude
			end
		end
	end
	if #seeTargets > 0 then
		dist = 35
		for i,v in ipairs(seeTargets) do
			if (humanoidrootpart.Position - v.Position).magnitude < dist then
				target = v 
				dist = (humanoidrootpart.Position - v.Position).magnitude
			end
		end
	end
	return target
end

function checkSight(target)
	local ray = Ray.new(humanoidrootpart.Position, (target.Position - humanoidrootpart.Position).Unit * 40)
	local hit,position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent}) 
	if hit then
		if hit:IsDescendantOf(target.Parent) and math.abs(hit.Position.Y - humanoidrootpart.Position.Y) < 3 then
			foundtarget = 1
			return true
		end
	end
	return false
end


function main()
	local target = FindTarget() 
	if target and foundtarget == 1 then
		humanoid.WalkSpeed = 35
		findPath(target)
	else
		humanoid.WalkSpeed = 22
		walkRandomly()
	end
end

while wait() do
	main() 
end

Hope this helps

1 Like

i mean i don’t know the way you want it to act, so i can’t put it anywhere inside the script without knowing the way you want it

use humanoidRootpart.

use my example
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new( – your position )

i somewhat edited your script, and the same exact problem happened
code:

local pathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
local foundtarget = nil
local targetpos = nil

local humanoid = script.Parent.Humanoid
local humanoidrootpart = script.Parent.HumanoidRootPart
local body = script.Parent:FindFirstChild("Torso")
local points = game.Workspace.Path:GetChildren()
humanoidrootpart:SetNetworkOwner(nil)


foundtarget = nil

function walkRandomly()
	local point = points[math.random(1,#points)]
	local target = FindTarget()
	local path = game:GetService("PathfindingService"):CreatePath()
	path:ComputeAsync(humanoidrootpart.Position, point.Position)
	local waypoints = path:GetWaypoints()
	for _, waypoint in ipairs(waypoints) do
		humanoid:MoveTo(waypoint.Position)
		if foundtarget == 1 then break end
		humanoid.MoveToFinished:Wait()
		FindTarget()
	end
end

function findPath(target)
	local path = game:GetService("PathfindingService"):CreatePath()
	path:ComputeAsync(humanoidrootpart.Position,target.Position)
	local waypoints = path:GetWaypoints()

		for _, waypoint in ipairs(waypoints) do
			humanoid:MoveTo(waypoint.Position)
			if checkSight(target) == true then
				repeat
					humanoid:MoveTo(target.Position)
					task.wait()
					if target == nil then
						break
					elseif target.Parent == nil then
						break
					end
			until checkSight(target) == false
			foundtarget = nil
				break
			end
			if (humanoidrootpart.Position - waypoints[1].Position).magnitude > 30 then
				findPath(target)
				break
			end
		end
	end

function FindTarget()
	local dist = 50
	local target
	local potentialTargets = {}
	local seeTargets = {}
	local players = game.Players:GetPlayers()


	for i,v in pairs(players) do
		if (v.Character) then
			local torso = v.Character.Torso
			local human = v.Character.Humanoid
			if (humanoidrootpart.Position - torso.Position).magnitude < dist and human.Health > 0 then
				table.insert(potentialTargets,torso)
			end
		end
	end
	if #potentialTargets > 0 then
		for i,v in ipairs(potentialTargets) do
			if checkSight(v) then	
				table.insert(seeTargets, v)
			elseif #seeTargets == 0 and (humanoidrootpart.Position - v.Position).magnitude < dist then
				target = v 
				dist = (humanoidrootpart.Position - v.Position).magnitude
			end
		end
	end
	if #seeTargets > 0 then
		dist = 35
		for i,v in ipairs(seeTargets) do
			if (humanoidrootpart.Position - v.Position).magnitude < dist then
				target = v 
				dist = (humanoidrootpart.Position - v.Position).magnitude
			end
		end
	end
	return target
end

function checkSight(target)
	local ray = Ray.new(humanoidrootpart.Position, (target.Position - humanoidrootpart.Position).Unit * 40)
	local hit,position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent}) 
	if hit then
		if hit:IsDescendantOf(target.Parent) and math.abs(hit.Position.Y - humanoidrootpart.Position.Y) < 3 then
			foundtarget = 1
			return true
		end
	end
	return false
end


function main()
	local target = FindTarget() 
	if target and foundtarget == 1 then
		humanoid.WalkSpeed = 35
		findPath(target)
	else
		humanoid.WalkSpeed = 16
		walkRandomly()
	end
end

RunService.Heartbeat:Connect(function()
	main() 
end)

I’m pretty sure it’s because you are using get children for getting your points, I don’t think you can do points[math.random(1,#points)] because of this, this is why I had each point individually in a table, so I can use arrays for a random point, what you can do is

local destination = game.Workspace.Path:GetChildren()
local points = {}
for point,_ in pairs(destination) do
table.insert(points,point)
end

This is so you don’t have to manually type in each point for the table, also this might not work properly because I can’t test it right now

well how should i replace that into this part of the code

local pathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
local foundtarget = nil
local targetpos = nil

local humanoid = script.Parent.Humanoid
local humanoidrootpart = script.Parent.HumanoidRootPart
local body = script.Parent:FindFirstChild("Torso")
local points = game.Workspace.Path:GetChildren()
humanoidrootpart:SetNetworkOwner(nil)


foundtarget = nil

function walkRandomly()
	local point = points[math.random(1,#points)]
	local target = FindTarget()
	local path = game:GetService("PathfindingService"):CreatePath()
	path:ComputeAsync(humanoidrootpart.Position, point.Position)
	local waypoints = path:GetWaypoints()
	for _, waypoint in ipairs(waypoints) do
		humanoid:MoveTo(waypoint.Position)
		if foundtarget == 1 then break end
		humanoid.MoveToFinished:Wait()
		FindTarget()
	end
end

Should be something like this

local pathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
local foundtarget = nil
local targetpos = nil

local humanoid = script.Parent.Humanoid
local humanoidrootpart = script.Parent.HumanoidRootPart
local body = script.Parent:FindFirstChild("Torso")

local destination = game.Workspace.Path:GetChildren()
local points = {}
for point,_ in pairs(destination) do
table.insert(points,point)
end

humanoidrootpart:SetNetworkOwner(nil)


foundtarget = nil

function walkRandomly()
	local point = points[math.random(1,#points)]
	local target = FindTarget()
	local path = game:GetService("PathfindingService"):CreatePath()
	path:ComputeAsync(humanoidrootpart.Position, point.Position)
	local waypoints = path:GetWaypoints()
	for _, waypoint in ipairs(waypoints) do
		humanoid:MoveTo(waypoint.Position)
		if foundtarget == 1 then break end
		humanoid.MoveToFinished:Wait()
		FindTarget()
	end
end

i got the error: 25: attempt to index number with 'Position'

here is my full script:

local pathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
local foundtarget = nil
local targetpos = nil

local humanoid = script.Parent.Humanoid
local humanoidrootpart = script.Parent.HumanoidRootPart
local body = script.Parent:FindFirstChild("Torso")

local destination = game.Workspace.Path:GetChildren()
local points = {}
for point,_ in pairs(destination) do
	table.insert(points,point)
end

humanoidrootpart:SetNetworkOwner(nil)


foundtarget = nil

function walkRandomly()
	local point = points[math.random(1,#points)]
	local target = FindTarget()
	local path = game:GetService("PathfindingService"):CreatePath()
	path:ComputeAsync(humanoidrootpart.Position, point.Position)
	local waypoints = path:GetWaypoints()
	for _, waypoint in ipairs(waypoints) do
		humanoid:MoveTo(waypoint.Position)
		if foundtarget == 1 then break end
		humanoid.MoveToFinished:Wait()
		FindTarget()
	end
end

function findPath(target)
	local path = game:GetService("PathfindingService"):CreatePath()
	path:ComputeAsync(humanoidrootpart.Position,target.Position)
	local waypoints = path:GetWaypoints()

		for _, waypoint in ipairs(waypoints) do
			humanoid:MoveTo(waypoint.Position)
			if checkSight(target) == true then
				repeat
					humanoid:MoveTo(target.Position)
					task.wait()
					if target == nil then
						break
					elseif target.Parent == nil then
						break
					end
			until checkSight(target) == false
			foundtarget = nil
				break
			end
			if (humanoidrootpart.Position - waypoints[1].Position).magnitude > 30 then
				findPath(target)
				break
			end
		end
	end

function FindTarget()
	local dist = 50
	local target
	local potentialTargets = {}
	local seeTargets = {}
	local players = game.Players:GetPlayers()


	for i,v in pairs(players) do
		if (v.Character) then
			local torso = v.Character.Torso
			local human = v.Character.Humanoid
			if (humanoidrootpart.Position - torso.Position).magnitude < dist and human.Health > 0 then
				table.insert(potentialTargets,torso)
			end
		end
	end
	if #potentialTargets > 0 then
		for i,v in ipairs(potentialTargets) do
			if checkSight(v) then	
				table.insert(seeTargets, v)
			elseif #seeTargets == 0 and (humanoidrootpart.Position - v.Position).magnitude < dist then
				target = v 
				dist = (humanoidrootpart.Position - v.Position).magnitude
			end
		end
	end
	if #seeTargets > 0 then
		dist = 35
		for i,v in ipairs(seeTargets) do
			if (humanoidrootpart.Position - v.Position).magnitude < dist then
				target = v 
				dist = (humanoidrootpart.Position - v.Position).magnitude
			end
		end
	end
	return target
end

function checkSight(target)
	local ray = Ray.new(humanoidrootpart.Position, (target.Position - humanoidrootpart.Position).Unit * 40)
	local hit,position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent}) 
	if hit then
		if hit:IsDescendantOf(target.Parent) and math.abs(hit.Position.Y - humanoidrootpart.Position.Y) < 3 then
			foundtarget = 1
			return true
		end
	end
	return false
end


function main()
	local target = FindTarget() 
	if target and foundtarget == 1 then
		humanoid.WalkSpeed = 35
		findPath(target)
	else
		humanoid.WalkSpeed = 16
		walkRandomly()
	end
end

RunService.Heartbeat:Connect(function()
	main() 
end)