NPC returning back and coming to the place he was?

Hello devs!

I’m trying to create a AI that turns on the light whenever the player turns off. But i’m having some problems on making it.

The npc returns normally to where he is but he comes back to the lightswitch after that.

Heres the code:

local npc = script.Parent

local goal = workspace.LightSwitch.WalkTo

local OldPos = Instance.new("Part")
OldPos.Position = script.Parent.HumanoidRootPart.Position
OldPos.Transparency = 1
OldPos.CanCollide = false

local pathfinding = game:GetService("PathfindingService")


function WalkToSwitch()
	local path = pathfinding:CreatePath()
	path:ComputeAsync(npc.HumanoidRootPart.Position, goal.Position)

	local waypoints = path:GetWaypoints()
	
	for i, waypoint in pairs(waypoints) do

		if waypoint.Action == Enum.PathWaypointAction.Jump then

			npc.Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
		end

		npc.Humanoid:MoveTo(waypoint.Position)

		npc.Humanoid.MoveToFinished:Wait()

	end
	
	if goal.Parent.IsOn.Value == true then
		print("Seriously?!?!?!")
		wait(1)
	elseif goal.Parent.IsOn.Value == false then
		goal.Parent.IsOn.Value = true
		wait(1)
	end
	
	local path2 = pathfinding:CreatePath()
	path2:ComputeAsync(npc.HumanoidRootPart.Position, OldPos.Position)

	local waypoints = path:GetWaypoints()

	for i, waypoint in pairs(waypoints) do

		if waypoint.Action == Enum.PathWaypointAction.Jump then

			npc.Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
		end

		npc.Humanoid:MoveTo(waypoint.Position)

		npc.Humanoid.MoveToFinished:Wait()

	end
end

while wait(0.1) do
	if goal.Parent.IsOn.Value == false then
		print("Who turned the lights off!")
		wait(1)
		WalkToSwitch()
	end
end

Make sure you anchor your OldPos part, or else it’ll fall off the map and move. (Cancollide is off so it’ll fall off the map)

I’ve did that, He still returns back

Hmm, why are you using a loop for WalkToSwitch()? You could just make a :GetPropertyChangedSignal() for the goal.Parent.IsOn.Value

Hmm, I’m not sure how to use that correctly, Give me a second.

It seems like that did not work also, It’s the pathfinding script’s problem

image
Doesn’t the bottom :MoveTo() just move it back to the waypoint, unless i’m not really understanding here

The “waypoint” thing is something that is required for pathfinding, Basically generates a path to anywhere

1 Like