I’m trying to make a chase system for a NPC, although It seems the contents from the Magnitudes
dictionary seem to be recognized as nil.
local PFS = game:GetService('PathfindingService')
local NPC = script.Parent
local Hum = NPC:FindFirstChild('Humanoid')
local HRP = NPC:FindFirstChild('HumanoidRootPart')
local Players = game:GetService('Players')
function GetNearestHRP()
local NearestCharacter
local function GetMagnitudes()
local Magnitudes = {}
for _, Player in pairs(Players:GetPlayers()) do
local Character = Player.Character or Player.CharacterAdded:Wait()
local CharHRP = Character:FindFirstChild('HumanoidRootPart')
if CharHRP then
print('Has humanoid root part')
Magnitudes[Player.Name] = (CharHRP.Position - HRP.Position).Magnitude
print(Magnitudes[Player.Name])
end
end
return Magnitudes
end
local Magnitudes = GetMagnitudes()
local function GetNearestCharacterName()
for PlrName, Magnitude in pairs(Magnitudes) do
if math.min(table.unpack(Magnitudes)) == Magnitude or #Players:GetPlayers() == 1 then -- :33: missing argument #1 to 'min' (number expected)
return PlrName
end
end
end
NearestCharacter = Players:FindFirstChild(GetNearestCharacterName()).Character or Players:FindFirstChild(GetNearestCharacterName()).CharacterAdded:Wait()
return NearestCharacter:FindFirstChild('HumanoidRootPart')
end
function SetupPathfinding(Origin, End)
local Path = PFS:CreatePath()
Path:ComputeAsync(Origin, End)
local Waypoints = Path:GetWaypoints()
for _, Waypoints in pairs(Waypoints) do
Hum:MoveTo(Waypoints.Position)
end
end
while wait(1) do
local Succ, NearestHRP = pcall(GetNearestHRP)
if Succ and NearestHRP then
SetupPathfinding(HRP.Position, NearestHRP.Position)
else
print(NearestHRP) -- :33: missing argument #1 to 'min' (number expected)
end
end
The part print(NearestHRP)
(Which after some checks, supposedly is a error) prints that the argument #1 of math.min
is missing, although it shouldn’t be, because I passed Magnitudes but unpacked.
Suggestions to improve the code are also welcome.