Issues with getting a player from player name

Here’s the script… take note of the prints.

print(target) -- prints
if game.Players:GetUserIdFromNameAsync(target) ~= nil then
	print("Match") -- prints
	print(game.Players:GetUserIdFromNameAsync(target)) -- prints correctly
	local p = game.Players:GetPlayerByUserId(game.Players:GetUserIdFromNameAsync(target))
	table.insert(sorted_a, p)
	print(p.Name)  -- attempt to index nil with 'Name'
	found = true
end

Anyone know what’s wrong?

If a.Name is printing “nil”. Then a doesnt exist.

Oops! Printed the wrong variable name. Editing the post now.

Finished editing… @TheEmeraIdDev

Try replacing the local p with this:

local p = game.Players:GetPlayerByUserId(target)

Target is a string.
E.g “TheEmeraldDev”

If the player ur trying to get isn’t in the game, it returns nil. I suggest u use a roblox api to get the username of a player thats not in the current game

2 Likes

Target is the name of the player, I am trying to get the actual player.

Trying to get the player object from a player’s name that is not in the game.

if the player isn’t in the game, there won’t be a player object

Why not? If I am using GetPlayerFromUserId it should work… Shouldn’t it?

What variables do you got? (30 char)

Just the target one… Which is the name of our target players username.

So for example if it were me, all you got is “Diamond_Plus1”?

Yes. That is correct.

Because the player isn’t in the server, there is not a player object for them

You might want to check out this article:

EDIT: sorry wrong link lol, i edited it

1 Like

local playerName = “Diamond_Plus1”
local function getPlayerFromUserName(name)
for _, v in pairs(game.Players:GetPlayers()) do
if v.Name == name then
return v
end
end

print(getPlayerFromUserName(playerName))

I think your solution is better as it doesn’t have to loop through stuff. @Winky_y this is the solution

the player isn’t in the server tho, so the only way of getting the userid of a player that isn’t in the server is to send a query to the roblox api

I’m confused the player is always on the server? It is replicated on the client.