Will this, 'ClosestObject,' module work?

Hey, the name’s Pumpy, also known as Pumpstormz. I need feedback on this, ‘ClosestObject,’ ModuleScript I’m working on. I’m unable to test it, because I don’t have my PC available at the moment, so if you could help I’d really appreciate it.

Here’s the ModuleScript:

local module = {}

function module:ClosestObj(obj, root)
	while wait() do
		local closestObj
		local maxDistance = math.huge
		if not closestObj then
			for i, v in pairs(workspace:GetDescendants()) do
				if v.Name == obj then
					local goal = v
					local magnitude = (root.Position - goal.Position).magnitude
					if magnitude < maxDistance then
						closestObj = goal
						print(closestObj)
					end
				end
			end
		end
	end
end

return module

Basically when I call the function, I would put the name of the object as a string for the first perimeter, and for the second I would put Character’s HumanoidRootPart. Let me know if I did anything wrong.

Yes, it will work. But some optimizations would be necessary, such as not doing workspace:GetDescendants() but using tags and CollectionService. This will decrease the amount of objects to loop through exponentially, because the “Objects” are already in an array and you just need to loop through that array.

1 Like

Alright, I’ll take that into consideration. Thank you for the feedback.

i also would remove this part of your code and make it a constant.

local maxDistance = math.huge

you don’t need to keep calculating a max distance if you want it to be endless; you can just do it once, outside the function and that will speed things up.

1 Like

Alright, thank you for the feedback.