How to find the nearest part(number) the player is sitting next to?

Hi, I want to find out how I can find the nearest said part the local player is sitting at. For example, if I have part1 to 16, I need to find the part closest to the player, like part 4 being the closest. How would I achieve this? Thanks.

i think I made it confusing sorry

3 Likes

I’m pretending there’s a folder in workspace containing all the parts.

local player = game.Players.LocalPlayer --Or if this is a server script, however you would get the player.
local Folder-Containing-Parts = game.Workspace.Folder
local Parts = Folder-Containing-Parts:GetChildren()

for _, p in pairs(Parts) do

if distance ~= nil and player:DistanceFromCharacter(p) > distance then 
distance = player:DistanceFromCharacter(p)
ClosestPart = p
end

If distance == nil then
distance = player:DistanceFromCharacter(p)
end

end
print(ClosestPart.Name)

Idk if it will work, and if it does it’s probably not the best way, but hope this helps!

2 Likes

You can use player:DistanceFromCharacter() which returns how many studs away is the vector3 from the player.

put the parts in a folder and try something like this:

local NearestPart = nil
local Lenght = nil
local Folder = workspace.Folder
local Player = game.Players.LocalPlayer

wait(10)

for i,v in pairs(Folder:GetChildren()) do
local LenghtX = Player:DistanceFromCharacter(v.Position)
	if Lenght == nil or LenghtX < Lenght then
		Lenght = LenghtX
		NearestPart = v
	end
end

print(NearestPart.name)

This script prints the name of the closest part after 10 seconds.
The NearestPart will be the nearest part to the player inside of the folder.

2 Likes

Lol, your script is almost a replica of mine

1 Like

we started making it at the same time :slight_smile:

1 Like

Ik, you were making your post before I started mine, I just noticed we basically told him the same stuff

1 Like