Can Someone Fix This Script For Me I Need It Where It Teleport's To Me The Nearest Object
for i,v in pairs(game.Workspace:GetDescendats()) do if v.Name == "Object" then v.CFrame = game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame * CFrame.new(0,0,-3.7) end end
You need to have a variable with the closest object's position in it and if you find a closer object putting it into that variable. Then, when the loop is done, teleport the player to the object in the variable. You can use Magnitude
to find the distance. Here is an example:
local players = game:GetService("Players") -- this is the recommended method for getting the service players local player = players.LocalPlayer local closestDistanceFound -- will define this in the loop local teleportPosition -- same as ^ local character = player.CharacterAdded:Wait() -- gonna wait for the character local humanoidRootPart = character.HumanoidRootPart -- this is the part of the player we will be using to teleport wait(5) -- wait for everything to load in for this example for i,v in pairs(game.Workspace:GetDescendants()) do if v.Name == "Object" then -- if you just want to see if it is a basepart you could do if v:IsA("BasePart") then local distanceFromPlayer = (v.Position - humanoidRootPart.Position).Magnitude if not closestDistanceFound then if closestDistanceFound > distanceFromPlayer then closestDistanceFound = distanceFromPlayer teleportPosition = v.Position end else closestDistancFound = distanceFromPlayer teleportPosition = v.Position end end end humanoidRootPart.CFrame = CFrame.new(teleportPosition)
I hope this helps and have a great day scripting!