Can you review my simple NPC tracking system and give me some tips and what I should improve on?

Code Review

NPCModule

local PathfindingService = game:GetService("PathfindingService")
local module = {}
module.__index = module


function module.new()
	local self = setmetatable({}, module)
	self.NPC = game.Workspace.Rig or self.NPC
	self.AgroDistance = 35 or self.AgroDistance
	self.Wandering = false or self.Wandering
	self.Target = nil or self.Target
	return self
end

function module:FindTarget()
	print("im a simga")
	local Distance = self.AgroDistance
	local Target = self.Target
	local Humanoid = self.NPC.Humanoid
	local HRP = self.NPC.HumanoidRootPart
	local NPC = self.NPC
	local WalkAnim = Humanoid:LoadAnimation(NPC.Animate.walk.WalkAnim)
	
	local function getPath()
		local path = PathfindingService:CreatePath()
		path:ComputeAsync(self.NPC.HumanoidRootPart.Position,Target.Position)
		return path
	end
	for _, player in pairs(game.Players:GetPlayers()) do
		print("Hi")
		if player.Character then
			print("Sigma phase 2")
			local targetRoot = player.Character:FindFirstChild("HumanoidRootPart")
			if targetRoot then
				print("Sigma Phase 3")
				local newDistance = (targetRoot.Position - self.NPC.HumanoidRootPart.Position).Magnitude
				if newDistance <= Distance then
					Target = targetRoot
					print("Sigma Phase 3 "..Target.Parent.Name)
					self.Target = Target
					task.spawn(function()
						if Target ~= nil then
						HRP:SetNetworkOwner(player)
						while task.wait() do
							if newDistance > Distance then
								Target = nil
								print("Walked out of range cooked.")
							else
								print("Sigma Phase 4 computing")
								if Target and Target.Parent.Humanoid.Health > 0 then
									local path = getPath()
									for _, waypoint in pairs(path:GetWaypoints()) do
										if Target == nil then return end
										if waypoint.Action == Enum.PathWaypointAction.Jump then
											Humanoid.Jump = true
										end
										if Humanoid.MoveDirection.Magnitude > 0 then
											WalkAnim:Play()
											
										end
										Humanoid:MoveTo(waypoint.Position)
									end
								end
							end
						end
					end
					end)
					return Target
				end
			end
		end
	end
	
end


return module

Server Script

local NPCModule = require(game.ServerScriptService.NPCModule)

local NPC = NPCModule.new()
NPC.NPC = script.Parent
local Player
game.Players.PlayerAdded:Connect(function(player)
	Player = player
	Player.CharacterAdded:Wait()
	NPC:FindTarget()
end)


print("bro!")
3 Likes