Get Character From Username

  1. What do you want to achieve? A function that gets the character from a username

  2. What is the issue? My function that gets a character from a username fails and I don’t know why

function GetCharacter(UserName)
	local UserId = players:GetUserIdFromNameAsync(UserName)
	local player = players:GetPlayerByUserId(UserId)
	local character = player.Character or player.CharacterAdded:wait()
	return character
end

How do I fix it?

UserName might be defined as nil depending on how you’re calling it, try adding print statements the moment you see that function being called

function GetCharacter(UserName)
	local UserId = players:GetUserIdFromNameAsync(UserName)
	local player = players:GetPlayerByUserId(UserId)
	local character = player.Character or player.CharacterAdded:Wait
    print(UserId)
    print(player)
    print(character)


	return character
end

local Char = GetCharacter(Player.Name)

if Char then
    print("Found a character")
else
     warn("Bruh")
end
1 Like

You could just call :FindFirstChild() with the player name as the first argument in workspace, or call it in game.Players.

Example:

local character = Workspace:FindFirstChild(PlrNameHere)
-- or
local character = game:GetService("Players"):FindFirstChild(PlrNameHere).Character

Edit: @JackscarIitt’s method is far more reliable, so if you can you should use his method.

1 Like

Are you trying to get the character of a player in-game? If so,

local Players = game:GetService("Players")

local function GetCharacter(name, waitForCharacter) --[[ waitForCharacter is a bool telling us whether you 
want to wait for the character if it doesnt exist ]]
  local Player = game.Players:FindFirstChild(name)
  if not Player then return nil end
  if waitForCharacter then
    local character = player.Character or player.CharacterAdded:Wait()
    return character
  else
    local character = player.Character
    return character
  end
end
3 Likes