PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

GetNameFromUserIdAsync

The GetNameFromUserIdAsync Players function will send a query to the Roblox website asking what the username is of the account with the given Player/UserId|UserId. This function does not cache; it always sends a web request even if a UserId was already queried or if the player is already connected to the server (and thus has their username exposed).

This method errors if no account exists with the given UserId. If you aren’t certain such an account exists, it’s recommended to wrap calls to this function with pcall. In addition, you can manually cache results to make future calls with the same UserId fast. See the code samples to learn how to do this.

Parameters

Name Type Default Description

The userId of the player being specified.

Returns

Return Type Summary

The name of a user with the specified userId.


Code Samples


Fast Username Lookup

This code sample demonstrates memoization (not memorization!) of the Players/GetNameFromUserIdAsync method. It uses a table to cache the results of the function. It also uses pcall in case the UserId doesn’t exist.

local Players = game:GetService("Players")

-- Memoization: since these results are rarely (if ever) going to change
-- all we have to do is check a cache table for the UserId.
-- If we find the UserId, then we have no work to do! Just return the name (fast).
-- If we don't find the UserId (cache miss), go look it up (takes time).
local cache = {}
function getUsernameFromUserId(userId)
	-- First, check if the cache contains the name
	if cache[userId] then return cache[userId] end
	-- Second, check if the user is already connected to the server
	local player = Players:GetPlayerByUserId(userId)
	if player then
		cache[userId] = player.Name
		return player.Name
	end 
	-- If all else fails, send a request
	local name
	pcall(function ()
		name = Players:GetNameFromUserIdAsync(userId)
	end)
	cache[userId] = name
	return name
end

print(getUsernameFromUserId(269323)) --> Ozzypig
print(getUsernameFromUserId(269323)) --> Ozzypig, but this one returns much quicker
print(getUsernameFromUserId(261)) --> Shedletsky