AI Passengers finding the closest part with a certain name when prompted

Hello, I’ve been trying to develop a basic NPC passenger system for vehicle simulation, and I haven’t been able to get past this part yet. Currently, my NPC is able to recognize when it’s time to board the vehicle, and do so. The script for this is


local NPC = script.Parent
local humanoid = NPC.Humanoid

game.ServerStorage.BoardingEvents.TestStationBoarding.Event:Connect(function()
	local pointA = game.Workspace.Train.DoorTargetTest
	humanoid:MoveTo(pointA.Position)
end)

I need to make the NPC find the closest part named ‘DoorTarget’ to it so it can board through the closest door, but I don’t know how to sort specifically though these named parts. I assume I’ll be using a :DistanceFromCharacter for this. Every DoorTarget part is in the same model. If anyone knows how to make the NPC sort through all the DoorTarget parts and find the closest one to it, that would be extremely helpful, thanks!

You could loop through each of your DoorTargets and then find the closest one by doing a magnitude check. I also use a maxDistance variable so we don’t search anything that’s further than 100 studs away.

local maxDistance = 100
local nearestDoor

for i, door in ipairs(Doors) do
	local distance = (NPC.PrimaryPart.Position - door.Positon).magnitude
	if distance < maxDistance then
		nearestDoor = door
		maxDistance = distance
	end
end

if nearestDoor then
	humanoid:MoveTo(nearestDoor.Position)
end