I created a for pairs loop, and i ned the instance inside of it, i, to change some things, but i cant grab it out side the loop, and i can only run the code after the loop finishes, is there a way i can grab that player instance even after the for loop is done? Or even is there a a way to run code when the loop is finished without writing the code out of the loop code block? this is what i have right now:
plr = game.Players.PlayerAdded:Wait()
char = plr.CharacterAdded:Wait()
nearPlayers = {}
num = 1
while true do
wait(1)
for _,i in pairs(game.Players:GetPlayers()) do
table.insert(nearPlayers, num, (i.Character.HumanoidRootPart.Position - script.Parent.Parent.Parent.HumanoidRootPart.Position).magnitude)
num += 1
end
table.sort(nearPlayers, function(a,b)
return a < b
end )
if nearPlayers[1] <= 15 then
--print("player Found")
script.Parent.Value = nearPlayers[1]
print(script.Parent.Value)
end
table.clear(nearPlayers)
num = 1
--print(unpack(nearPlayers))
end
but the only part you need to look at (to make it less confusing to you) is thisW:
nearPlayers = {}
num = 1
for _,i in pairs(game.Players:GetPlayers()) do
table.insert(nearPlayers, num, (i.Character.HumanoidRootPart.Position - script.Parent.Parent.Parent.HumanoidRootPart.Position).magnitude)--sets a place in the array to a position of that player
num += 1
end
table.sort(nearPlayers, function(a,b) --sorts it by distance lest to greatest
return a < b
end )
if nearPlayers[1] <= 15 then--if the first one, the least one, is lower than 15 which means its close enough to the npc im running this script in, then this activates
--print("player Found")
script.Parent.Value = nearPlayers[1]
print(script.Parent.Value)
end
but it prints the location, which i had to do to sort it, not the player name, i cant think of a way to also get the player name out of the loop and have it also be sorted the same way.
i tried adding hte player name to the end of the value being put in the array and using tonumber on string.sub, but if it runs through the same position twice (meaning the player didnt move) then it doesnt work and says something about it being nil.
Example:
table.insert(nearPlayers, num, (i.Character.HumanoidRootPart.Position - script.Parent.Parent.Parent.HumanoidRootPart.Position).magnitude.. ";" ..i.Name)
table.sort(nearPlayers, function(a,b)
return tonumber( string.sub(a, 1, 15) ) < tonumber( string.sub(b, 1, 15) )
end )
the position goes up to 15 numbers btw thats why its 1 to 15.
pls help

2 comments
alright! this is genious I never thought of that, let me test this
wait so this is putting a table inside a table right? THIS IS GENIOUS THANK YOU I NEVER THOUGHT OF THIS