My values aren't being saved

Hello,

I’m making a data store script so Playtime’s value can be saved, weirdly both of the pcall functions will return true/ success. (Meaning that the data is being in sync with the player’s userId and the data / leader stats values is being saved as the player exits out.) But then when I rejoin the game my Playtime’s value = 0

local player = game:GetService("Players")
local dataservice = game:GetService("DataStoreService")
local datasaved = dataservice:GetDataStore("PlrData")
player.PlayerAdded:Connect(function(Player)
	local leader = Instance.new("Folder", Player)
	leader.Name = "leaderstats"

	local Tim = Instance.new("IntValue", leader)
	Tim.Name = "PlayTime"
	

	local data 
	local success, errorm = pcall(function()
		data = datasaved:GetAsync(Player.UserId.. "-PlayTime")
	end)

	if success then 
		Tim.Value = data
		print("Sucess")
	else
		print("NOt working ... " )
	end
end)

function savedata(Player)

	local success, errorm = pcall(function()
		datasaved:SetAsync( Player.UserId, Player.leaderstats.PlayTime.Value)
		print("Player's playtime saved", Player.leaderstats.PlayTime.Value)
	end)
	if success then 
		print("We saved IT!!!!!")
	else
		print("No save no slave")
		
	end
end
player.PlayerRemoving:Connect(function(savedata)
	
end)
game:BindToClose(function()
	for _, v in pairs(player:GetPlayers()) do 
		savedata(v)
	end
end)


You are using a different key when saving the data and loading the data

Key for saving: Player.UserId
Key for retrieving: Player.UserId .. "-PlayTime"

Make sure to use the same key.
Corrected code:

local player = game:GetService("Players")
local dataservice = game:GetService("DataStoreService")
local datasaved = dataservice:GetDataStore("PlrData")

player.PlayerAdded:Connect(function(Player)
    local leader = Instance.new("Folder", Player)
    leader.Name = "leaderstats"

    local Tim = Instance.new("IntValue", leader)
    Tim.Name = "PlayTime"

    local data 
    local success, errorm = pcall(function()
        data = datasaved:GetAsync(Player.UserId.. "-PlayTime")
    end)

    if success and data then 
        Tim.Value = data
        print("Success")
    else
        print("Not working ... " )
    end
end)

function savedata(Player)
    local success, errorm = pcall(function()
        datasaved:SetAsync(Player.UserId.. "-PlayTime", Player.leaderstats.PlayTime.Value)
        print("Player's playtime saved", Player.leaderstats.PlayTime.Value)
    end)
    if success then 
        print("We saved IT!!!!!")
    else
        print("No save no slave")
    end
end

player.PlayerRemoving:Connect(savedata)

game:BindToClose(function()
    for _, v in pairs(player:GetPlayers()) do 
        savedata(v)
    end
end)
1 Like

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