Script only works for a short amount of time?

i’ve got a script that handles pathfinding between the positions of 2 parts. the only thing is that it makes paths for a short period of time before stopping completely.

local pathfinding_service = game:GetService("PathfindingService")
local run_service = game:GetService("RunService")

local path
local waypoints

local test_part = workspace:WaitForChild("test_part")
local hostile_part = script.Parent

-- only works for a short period of time but throws no errors
run_service.Heartbeat:Connect(function()
	
	path = pathfinding_service:CreatePath({
		AgentRadius = 2,
		AgentHeight = 5
	})
	
	path:ComputeAsync(hostile_part.Position, test_part.Position)
	waypoints = path:GetWaypoints()

	for i, waypoint in ipairs(waypoints) do
		local path_part = Instance.new("Part")
		
		path_part.BrickColor = BrickColor.random()
		path_part.Material = Enum.Material.Neon
		path_part.Parent = workspace
		path_part.Anchored = true
		path_part.CanCollide = false
		path_part.Size = Vector3.new(0.3, 0.3, 0.3)
		path_part.Position = waypoint.Position

		game:GetService("Debris"):AddItem(path_part, 0.3)
	end
end)

I recommend you follow this guide. You shouldn’t be calling CreatePath within a RunService.Heartbeat connection. Instead you should utilize events to determine when a new path needs to be calculated.

2 Likes

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