How i can get A player random friend userId?
....
How i can get A player random friend userId?
....
Players:GetFriendsAsync returns pages of friends of specified user, when you get the pages, extract all user ids from them and insert them into a table in array form, when you have the table, you know size of it and you know that every user id has it's own whole index in range from 1 to amount of user ids in table, you can generate random number in this range and select index that matches randomly generated number from the array.
local Players = game:GetService("Players")
local function getRandomElement(array)
if #array == 0 then
return nil
end
return array[math.random(#array)]
end
local function getFriends(userId)
local friends = {}
local friendPages = Players:GetFriendsAsync(userId)
while true do
local currentPage = friendPages:GetCurrentPage()
for _, friend in pairs(currentPage) do
table.insert(friends, friend.Id)
end
if friendPages.IsFinished then
break
end
friendPages:AdvanceToNextPageAsync()
end
return friends
end
local friends = getFriends(652793987)
print(friends)
print(getRandomElement(friends))
If you want to get id of random friend that is currently in this server, you can loop through every player in the server and check if Player:IsFriendsWith the original player.
local Players = game:GetService("Players")
local function getRandomElement(array)
if #array == 0 then
return nil
end
return array[math.random(#array)]
end
local function getFriendsInServerAsync(userId)
local friends = {}
for _, player in ipairs(Players:GetPlayers()) do
if player:IsFriendsWith(userId) then
table.insert(friends, player.UserId)
end
end
return friends
end
local friends = getFriendsInServerAsync(652793987)
print(friends)
print(getRandomElement(friends))
This discussion is preserved as it was. New answers, comments, and votes are closed.