I scripted this system for when a player clicks a panic button it sends a message to a UiList. On the message, I want it to display the Player’s nearest location (which is represented by parts around the map with the location name’s as their part name). I used a print statement with using Magnitude to cycle through all the parts to see which one is closest. This works, I just don’t understand how I could tell the script to choose which part is closest.
Could you guys help point me in the right direction, thanks!
Server Script:
panicEvent.OnServerEvent:Connect(function(Player, Sender, Location)
for i, v in pairs(workspace.RadioLocators:GetChildren()) do
print((v.Position - Player.Character.PrimaryPart.Position).Magnitude)
end
panicEvent:FireAllClients(Sender, Location)
print(Player.Name.." has activated their panic button.")
end)
Hello there, its actually quite simple, you basically already did all of the work.
What you need is to define a variable that holds the value of the lowest distance so far, and compare it to the current loop’s distance. If its lower, overwrite it.
panicEvent.OnServerEvent:Connect(function(Player, Sender, Location)
local closest = math.huge --no number is greater than math.huge
for i, v in pairs(workspace.RadioLocators:GetChildren()) do
local currentdistance = (v.Position - Player.Character.PrimaryPart.Position).Magnitude
if currentdistance < closest then closest = currentdistance end
end
panicEvent:FireAllClients(Sender, Location)
print(Player.Name.." has activated their panic button.")
print("Closest distance is:",closest)
end)
I tested this and it doesn’t work… It false detected a part for being the closest- I believe this is because whichever part the script detects first is always going to return true because its < than math.huge. Whereas the script needs to cycle through all the parts before declaring which part is the closest.
I just checked- according to print statements, yes. It is cycling through all the parts but keeps printing this one part. Here, I updated the script to what you did:
panicEvent.OnServerEvent:Connect(function(Player, Sender, Location)
local maxLength = math.huge
local targetPart
for i, v in pairs(workspace.RadioLocators:GetChildren()) do
print(v)
local currentDistance = (v.Position - Player.Character.PrimaryPart.Position).Magnitude
if currentDistance < maxLength then
targetPart = v.Name
end
end
panicEvent:FireAllClients(Sender, targetPart)
print(Player.Name.." has activated their panic button.")
print("Closest Part: "..targetPart)
end)