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’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!
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.