I'm trying to save 4 leaderstats in a DataStore using Tables. For some reason, only the first two leaderstats(Energy and Credits) are saving. I also have a problem where when a player joins the game the Speed leaderstat is going straight to zero. There are no errors and i have tried it in Studio and the actual game, and still the same problem. Could anybody help?
Heres the code
local DSS = game:GetService("DataStoreService") local AllDS = DSS:GetDataStore("AllDataStore") game.Players.PlayerAdded:Connect(function(player) local stats = Instance.new("Folder") stats.Name = "leaderstats" stats.Parent = player local hidden = Instance.new("Folder") hidden.Name = "hidden" hidden.Parent = player local Energy = Instance.new("IntValue") Energy.Name = "Energy" Energy.Value = 1 Energy.Parent = stats local Credits = Instance.new("IntValue") Credits.Name = "Credits" Credits.Value = 1 Credits.Parent = stats local Speed = Instance.new("IntValue") Speed.Name = "Speed" Speed.Parent = stats Speed.Value = 8 local Jump = Instance.new("IntValue") Jump.Name = "Jump" Jump.Value = 70 Jump.Parent = hidden local playerUserId = "Player_"..player.UserId local data local success, errormessage = pcall(function() data = AllDS:GetAsync(playerUserId) end) if success then Energy.Value = data.Energy Credits.Value = data.Credit Speed.Value = data.Speed Jump.Value = data.Jump end end) game.Players.PlayerRemoving:Connect(function(player) local playerUserId = "Player_"..player.UserId local data = { Energy = player.leaderstats.Energy.Value; Credits = player.leaderstats.Credits.Value; Speed = player.leaderstats.Speed.Value; Jump = player.hidden.Jump.Value; } local success, error,essage = pcall(function() AllDS:SetAsync(playerUserId, data) end) if success then print("Data was saved") else print("Did not save") warn(errormessage) end end)
Typos:
Credits.Value = data.Credit
when Credits = player.leaderstats.Credits.Value;
I think it errored there, so that's why it's not loading the other stats.
Btw, fix:
local success, error,essage = pcall(function()
To fix the problem where leaderstats are set to 0, put this after your data = AllDS:GetAsync(playeruserid):
if data == nil then error("No data in save file; keeping default stats...") end
This should fix it.
By the way, you should reset your save file by using AllDS:RemoveAsync(playeruserid)
to test this.
And finally, make sure you have Enable Studio Access To API Services on in Game Settings so you can use DataStore in Studio.