Im using a save data script for my simulator where it saves the amount of strength and the amount of coins you have but it doesn’t seem to be working and no errors come up once i start the game but the data doesn’t save
Just like @Wizard101fire90 mentioned, you are using GetAsync instead of SetAsync. GetAsync gets the data from a datastore, while SetAsync sets it (or stores it). When the player leaves, use SetAsync.
-- Variables --
local DataStoreService = game:GetService("DataStoreService")
local SaveData = DataStoreService:GetDataStore("SaveData")
local Players = game:GetService("Players")
-- Scripting --
Players.PlayerAdded:connect(function(Player)
local PlayerKey = "id_"..Player.UserId
local Leaderstats = Instance.new("Folder")
Leaderstats.Name = "leaderstats"
Leaderstats.Parent = Player
local Strength = Instance.new("IntValue")
Strength.Name = "Strength"
Strength.Parent = Leaderstats
local Coins = Instance.new("IntValue")
Coins.Name = "Coins"
Coins.Parent = Leaderstats
local SavedStrength
local Success, ErrorMessage = pcall(function()
SavedStrength = SaveData:GetAsync(PlayerKey.."_strength")
end)
if Success then
if SavedStrength ~= nil then
Strength.Value = SavedStrength
else
Strength.Value = 0
end
else
warn("Error getting saved strength for "..Player.Name..". Error: "..ErrorMessage)
end
local SavedCoins
local Success2, ErrorMessage2 = pcall(function()
SavedCoins = SaveData:GetAsync(PlayerKey.."_coins")
end)
if Success2 then
if SavedCoins ~= nil then
Coins.Value = SavedCoins
else
Coins.Value = 0
end
else
warn("Error getting saved coins for "..Player.Name..". Error: "..ErrorMessage2)
end
end)
Players.PlayerRemoving:connect(function(Player)
local PlayerKey = "id_"..Player.UserId
local Leaderstats = Player:WaitForChild("leaderstats")
local Strength = Leaderstats:WaitForChild("Strength")
local Coins = Leaderstats:WaitForChild("Coins")
local Success, ErrorMessage = pcall(function()
SaveData:SetAsync(PlayerKey.."_strength", Strength.Value)
end)
if not Success then
warn("Could not save player's "..Player.Name.." strength data. Error: "..ErrorMessage)
end
local Success2, ErrorMessage2 = pcall(function()
SaveData:SetAsync(PlayerKey.."_coins", Coins.Value)
end)
if not Success2 then
warn("Could not save player's "..Player.Name.." coin data. Error: "..ErrorMessage2)
end
end)
It is indeed a bit longer. I created the leaderstats folder and it’s children within this script since the value will be set there. Also, it has some checks in case an error occurs, which can happen. This should work. I will give it a test run and let you know.
Keep in mind, when solo testing, for some reason it does not always save it, so to get accurate results, join the actual game, change your stats, leave the game, and then join again.