I tried to make a NPC follow a player, but I am kind of confused about how Pathfinding works.
The output says:
Workspace.Dummy.Walk:58: attempt to index nil with ‘Position’ - Server - Walk:58
local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")
local Z = script.Parent:FindFirstChild("Humanoid")
local debounce = false
local e = false
local damage = 15
local pathfindingService = game:GetService("PathfindingService")
Anim = Z:LoadAnimation(script.Parent.Animation)
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 50
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("Torso")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
function Hit(hit)
local human = hit.Parent:FindFirstChild("Humanoid")
if human ~= nil then
if debounce then return end
debounce = true
human:TakeDamage(damage)
wait(1)
debounce = false
end
end
larm.Touched:connect(Hit)
rarm.Touched:connect(Hit)
while true do
wait(0.1)
local target = findNearestTorso(script.Parent.Torso.Position)
local path = pathfindingService:CreatePath()
path:ComputeAsync(script.Parent.Torso.Position, target.Position) -- error
local waypoints = path:GetWaypoints()
if target ~= nil then
for i, waypoint in pairs(waypoints) do
Z:MoveTo(waypoint.Position)
Z.MoveToFinished:Wait(1)
end
script.Parent.Humanoid:MoveTo(waypoints.Position)
if e == false then
Anim:Play()
e = true
end
end
end
Is there any way of that I can fix this?
(If I did anything wrong with this post please tell me)