That’s a much better improvement than your original code, however, there are certain things which you are doing every iteration within your for loop that need not be repeated.
for Index,Child in pairs(Model:GetChildren()) do
if (Core.Position - Child.Position).Magnitude == math.min(unpack(Position_Contain)) then
Every iteration of that for loop, math.min(unpack(Position_Contain)) is re-calculated. You could’ve calculated it before the 2nd for loop began and accessed it via variable as it only needs to be calculated once and doesn’t change throughout the second for loop. Also, unless the children in the model constantly change, you can call Model:GetChildren() outside of any loop for an improvement instead of using that method to get the same table every time.
Also, you can add a break statement to your for loop once it has found the closest object which signals it from iterating further (as the closest object has already been found).
The goal here is to minimise the number of operations per iteration and reduce the iteration count.
How I would do it is:
- Get and store a variable containing the children of Model and iterate over it’s contents.
- Have a “running” variable which updates throughout the course of a single for loop. This variable will represent the minimum distance found so far. Use a second variable to represent the object from which that distance was calculated.
- Once all children of the Model have been checked, return the closest object found.
local Model = workspace.Model
local Core = workspace.Core
local Contents = Model:GetChildren()
local MaxDistance = 30
local MinDistance = MaxDistance --Start off assuming the min. dist is the max and try to find smaller
for Index, Child in ipairs(Contents) do
local dist = (Child.Position - Core.Position).Magnitude --Prevent's calculating the distance twice per iter
if dist < MinDistance then
MinDistance, ClosestObject = dist, Child
--Has to check all objects without breaking as next object in next iteration could be closer
local Closest = GetDistanceFromChildren()
Overall, this has halved the number of iterations from your previous code.