Get player from their username

Assume that I have Player1 and Player2. Now, Player1 (admin) wants to rank up Player2. But, they (Player2) are not in the server.
So, my question is - can I somehow get the player instance only by their username and they are not on the current server?

1 Like

Oh, sorry. I didn’t do any research…

local Players = game:GetService("Players")

local playerNeeded = print(Players:GetPlayerByUserId(Players:GetUserIdFromNameAsync("Player2")))
print(playerNeeded.Name)
1 Like

Hey! I know it was already solved, but I made a module a bit back you can use:
Remember, this is for a module.

local pservice = game:GetService('Players')
return {
	getNameFromId = function(id)
		local e,r = pcall(function()
			return pservice:GetNameFromUserIdAsync(id)
		end)
		if(e) then
			return r
		else
			e,r = pcall(function()
				pservice:GetUserIdFromNameAsync(id)
				return nil
			end)
			if(e) then
				return pservice:GetNameFromUserIdAsync(pservice:GetUserIdFromNameAsync(id))
			else
				return nil
			end
		end
	end;
	GetIdFromUserName = function(id)
		id = tonumber(id) or id
		local e,r = pcall(function()
			return pservice:GetUserIdFromNameAsync(id)
		end)
		if(e) then
			return r
		else
			e,r = pcall(function()
				pservice:GetNameFromUserIdAsync(id)
				return nil
			end)
			if(e) then
				return pservice:GetUserIdFromNameAsync(pservice:GetNameFromUserIdAsync(id))
			else
				return nil
			end
		end
	end;
}
1 Like

Forgot to mention, you can feed either into each. As in, rezokar would return Rezokar for the name one and 182877115 for the id. Also useful for making sure names are capitalized properly.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.