I can't figure out how to access player data with ProfileService

Hello! I’m trying to make a player saving system but I can’t figure out how to access it.
Should I use a modulescript?

Code:

local ProfileTemplate = {
	totalXP = 1000, 
	points = 50, 
	isBugReportBanned = false
}

----- Loaded Modules -----

local ProfileService = require(game.ServerScriptService.ProfileService)

----- Private Variables -----

local PlayersService = game:GetService("Players")

local ProfileStore = ProfileService.GetProfileStore(
	"PlayerData",
	ProfileTemplate
)

local Profiles = {} -- [player] = profile

----- Private Functions -----
local function PlayerAdded(player)
	local profile = ProfileStore:LoadProfileAsync("Player_" .. player.UserId)
	if profile ~= nil then
		profile:AddUserId(player.UserId) -- GDPR compliance
		profile:Reconcile() -- Fill in missing variables from ProfileTemplate (optional)
		profile:ListenToRelease(function()
			Profiles[player] = nil
			-- The profile could've been loaded on another Roblox server:
			player:Kick()
		end)
		if player:IsDescendantOf(PlayersService) == true then
			Profiles[player] = profile
			-- A profile has been successfully loaded:
		else
			-- Player left before the profile loaded:
			profile:Release()
		end
		local DataLoaded = Instance.new("StringValue",player)
		DataLoaded.Name = "DataLoaded"
	else
		-- The profile couldn't be loaded possibly due to other
		--   Roblox servers trying to load this profile at the same time:
		player:Kick()
	end
end

----- Initialize -----

-- In case Players have joined the server earlier than this script ran:
for _, player in ipairs(PlayersService:GetPlayers()) do
	task.spawn(PlayerAdded, player)
end

----- Connections -----

game.ReplicatedStorage.Remotes.Stats.StatsUpdater.OnServerInvoke = function(player) -- For client-side access
	return Profiles[player]
end

PlayersService.PlayerAdded:Connect(PlayerAdded)

PlayersService.PlayerRemoving:Connect(function(player)
	local profile = Profiles[player]
	if profile ~= nil then
		profile:Release()
	end
end)

Thanks!

You can access the player’s data through Profiles[player].Data or use this function

function Get(player) -- get player data
 local profile = Profiles[player]
 if profile then -- check if it exists
  return profile.Data
 end
end

For use outside the script, yes you need to turn this into a module

1 Like

Thanks! I terribly misread the documentation.

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