I’m having some trouble trying to get the player’s data to save. The script it supposed to print when it gets the data and when the data is saved and it does that but doesn’t end up saving the data and I can’t figure out why.
local dss = game:GetService("DataStoreService")
local myData = dss:GetDataStore("myData")
game.Players.PlayerAdded:Connect(function(plr)
local money= plr:WaitForChild("leaderstats").Money
local data
local success, err = pcall(function()
data = myData:GetAsync(plr.UserId.."money", plr.leaderstats.Money.Value)
end)
if success then
money.Value = data
print("Success")
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
local data = plr.leaderstats.Money.Value
local success, err = pcall(function()
myData:SetAsync(plr.UserId.."_money", plr.leaderstats.Money.Value)
end)
if success then
print("Saved data")
else
print("There was a problem")
warn(err)
end
end)
local dataStores = game:GetService("DataStoreService")
local dataStore = dataStores:GetDataStore("DataStore")
local players = game:GetService("Players")
local protectedCall = pcall
players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local money = Instance.new("IntValue")
money.Name = "Money"
money.Parent = leaderstats
local success, result = protectedCall(function()
return dataStore:GetAsync("Money_"..player.UserId)
end)
if success then
if result then
money.Value = result
end
else
warn(result)
end
end)
players.PlayerRemoving:Connect(function(player)
local success, result = protectedCall(function()
return dataStore:SetAsync("Money_"..player.UserId, player.leaderstats.Money.Value)
end)
if success then
if result then
print(result)
end
else
warn(result)
end
end)
game:BindToClose(function()
for _, player in ipairs(players:GetPlayers()) do
local success, result = protectedCall(function()
return dataStore:SetAsync("Money_"..player.UserId, player.leaderstats.Money.Value)
end)
if success then
if result then
print(result)
end
else
warn(result)
end
end
end)
I merged the leaderstats creation and datastore saving/loading into a single script as that’s often best. I’ve also added “:BindToClose()” function because the “PlayerRemoving” event doesn’t fire in studio.