Attempt to index nil with 'DisplayName' (line 58)

My code:

local RespawnTimes = {
	Premium = 2;
	Norm = 4;
}

local Admins = {
	206143181;
}

game.Players.PlayerAdded:Connect(function(plr)
	
	plr:SetAttribute("Disguised",false)
	
	plr.CharacterAdded:Connect(function(Char)
		
		Char:WaitForChild("Humanoid").Died:Connect(function()
			
			if plr.MembershipType == Enum.MembershipType.Premium or table.find(Admins,plr.UserId) then
				
				task.wait(RespawnTimes.Premium)
				
				plr:LoadCharacter()
				
				print(plr.DisplayName .. " respawned quickly")
				
			else
				
				task.wait(RespawnTimes.Norm)

				plr:LoadCharacter()
				
			end
			
		end)
		
	end)
	
	plr.Chatted:Connect(function(msg)

		msg = string.lower(msg)

		local cmd = string.split(msg," ")[1]

		if cmd == "/disguise" and plr:GetAttribute("Disguised") == false then

			if plr.MembershipType == Enum.MembershipType.Premium or table.find(Admins,plr.UserId) then

				plr:SetAttribute("Disguised",true)
				
				local Hum = plr.Character:WaitForChild("Humanoid")
				
				local ChosenId = math.random(1,2000000000)
				
				Hum:ApplyDescription(game.Players:GetHumanoidDescriptionFromUserId(ChosenId))
				
				repeat task.wait() until workspace:FindFirstChild(plr.Name)
				
				workspace:FindFirstChild(plr.Name).Humanoid.DisplayName = game.Players:GetPlayerByUserId(ChosenId).DisplayName
				
			end

		end

	end)
	
end)

but i want to change the displayname only for in game

Just use the Hum variable


Changing their DisplayName in-game is not going to affect their account


The problem here is that you’re using Players:GetPlayerByUserId to fetch a user that’s not in the current session. If you want to get a player’s displayname, you need to use UserService:GetUserInfosByUserIdsAsync

-- Example
local userService = game:GetService("UserService")
local function getDisplayName(id: number) : string
   local success, output = pcall(function()
     -- this is an error catcher
     -- since this function is making a web request, it can error if Roblox's servers are down
     -- this prevents the error from breaking the script
     return userService:GetUserInfosByUserIdsAsync({id}) -- returns the user information
   end)

   if success and output[1] then -- if the web request was successful, return the player's displayname
      return output[1].DisplayName -- return the player's displayname
   end

   -- if the request wasn't successful, send a warning to output showing the error
   -- and just return "null" as a placeholder 
   warn(output)
   return "null"
end

print(getDisplayName(107157606)) --> prints "omega" (my displayname)
1 Like