Getting nearest part to show nearest road isn't working

  1. What do you want to achieve? I want to show the nearest road of the player on the bottom right

  2. What is the issue? It doesn’t detect the nearest road and only switches to the nearest when you walk away from the part, like it’s not detecting the part.

						if range == nil then
							range = (p.Character.HumanoidRootPart.Position - v.Position).Magnitude
							closest = v
						elseif range ~= nil then
							if (p.Character.HumanoidRootPart.Position - v.Position).Magnitude < range then
								closest = v
								range = (p.Character.HumanoidRootPart.Position - v.Position).Magnitude
							end
						end
						print(closest.Name)
						p.PlayerGui.GameInformationUI.venue.Text = closest.Name


This is what the parts look like

1 Like

Is that all the code?

Because of the lack of details of how you are checking the objects, I can only assume.


You may be having this issue because you aren’t Properly Checking what the closest road, a Single for isn’t perfect for this:

You should check the Ranges between the Parts by having a Variable to check if the Range is less than a Limit, if it returns true, that will be the new limit set, This is a good system as it will help you specify what part is actually nearer because a for loop isnt perfect, it puts the Instances in a Random order depending on their name, so this will make it so it will actually find the closest between limits.

Another Reason could be that there are smaller Parts Around, Looking at it, Smaller Parts tend to be closer to their center rather bigger parts.

You should also be using Player:DistanceFromCharacter instead of (Difference).Magnitude, it works the Exact same way:

range = p:DistanceFromCharacter(EndPos) -- Same thing
range = (StartPos - EndPos).Magnitude

Anyway, Here should be a better way to check if a Part is closer of not:

local maxDistance = math.huge -- has an infinite range at the start
local closest
local range
for _,v in Positions do -- whatever they are called to iterate through
    range = p:DistanceFromCharacter(v.Position) -- distance
    if range and range < maxDistance then -- is there is a range and is less than the max
        maxDistance = range -- new limit
        closest = v -- new object
    end
end

print(closest)
p.PlayerGui.GameInformationUI.venue.Text = closest

Thanks, it seems like the bigger parts are the ones that aren’t working as much due to the reason you stated that their center is closer, I don’t know what I should do to fix this.