GetPlayerByUserID returning nil, even when UserId is valid

I’m trying to create a global leaderboard to show the players with the most credits (ingame currency). But for some reason, whenever I try to use GetPlayerFromUserId on the entry’s key, it returns nil, even though when I put the entry’s key into a URL for a profile, it returns the user correctly.

Here is the script:

local datastore = game:GetService("DataStoreService")
local playerCredits = datastore:GetOrderedDataStore("credits")

local pages = playerCredits:GetSortedAsync(false, 25)
local entries = pages:GetCurrentPage()

local leaderboard = script.Parent
local cell = script.Cell

for index, entry in pairs(entries) do
	
	local user = game:GetService("Players"):GetPlayerByUserId(entry.key)

	local playerCell = cell:Clone()
	
	playerCell.Key.Text = index
	playerCell.Player.Text = user.Name
	playerCell.Credits.Text = entry.value
	
	playerCell.Parent = leaderboard.SurfaceGui.ScrollingFrame
end
1 Like

players:GetPlayerByUserId returns a Player object. If player is not currently in the server where the method is called, it will return nil.

1 Like

For Players:GetPlayerByUserId to work the player needs to be in game, i suggest using Players:GetNameFromUserIdAsync instead since you seem to only be getting the name

1 Like

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