Get nearest part

I think I’m doing it right but I’m not sure…


	for i,v in pairs(game.Workspace.Enemys:GetChildren()) do
		if (PLR.Character.HumanoidRootPart.Position - v.Position).Magnitude < 25 then
			---Do something.
		end
	end

What is the correct way to do this if I’m not doing it right.

4 Likes

You’ve left out an incredible amount of information. Please revise your post.

3 Likes

Yea, what are you trying to do with your code?

2 Likes

That is the correct way to go through parts to find ones that are near a player. You should keep parts that are going to be searched like this in their own workspace folder (it appears you already have). This is a good optimization because it reduce the number of parts to search.

I should add, that if your game has walls, and that matters for this search, then after you have culled the list to those within a specific range, you need to raycast from the player to the part to see if you have line of sight.

2 Likes

On each ‘successful’ iteration, you can update a variable that says what the distance to beat is, that way you’ll know the closest:

local range = 25
local closest

for _, enemy in ipairs(enemies) do
    local distance = (target.Position - enemy.PrimaryPart.Position).Magnitude

    if distance < range then
         range = distance -- set new 'distance to beat' to the current one

         closest = enemy
    end
end

print(closest)
8 Likes


Closest should be nil since I’m more than 25 away from the test enemy’s but its still coming up as TestEnemy4 even though I’m far far away, Do you know why this is happening?

(The cubes in the distance are the test enemy’s)

    for _, enemy in ipairs(game.Workspace.Enemys:GetChildren()) do
		local distance = (PLR.Character.HumanoidRootPart.Position - enemy.Position).Magnitude
		if distance < range then
			closest = enemy
		end
	end
	print(closest)
2 Likes

It’s because you didn’t add a replacement code for the meantime.

local range = 25
local closest

for _, enemy in ipairs(enemies) do
    local distance = (target.Position - enemy.PrimaryPart.Position).Magnitude

    if distance < range then
         range = distance -- set new 'distance to beat' to the current one

         closest = enemy
    elseif distance >= range then
        closest = nil
    end
end

print(closest)