local DataStoreService= game:GetService("DataStoreService") local myDataStore = DataStoreService:GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(player) local leaderstats = Instance.new("Folder") leaderstats.Name = "leaderstats" leaderstats.Parent = player local cash = Instance.new("IntValue") cash.Name = "cash"
cash.Parent = leaderstats local data local success, errormessage = pcall(function() data=myDataStore:GetAsync(player.UserId.."-cash") end) if success then cash.Value=data else print ("There was an error") warn (errormessage) end
end) game.Players.PlayerRemoving:Connect(function(player) local success, errormessage =pcall (function() myDataStore:SetAsync(player.UserId.."cash",player.leaderstats.cash.Value) end) if success then print ("Player data saved successfully") else print ("There was an error when saving data") warn(errormessage) end end)
your code actually looks great, the problem might actually be with when the data is retrieved.. you see, the when you retrieve data but that data hasn't yet been set, the function won't error, it will instead return nil
.. and looking at your code, this would logically interpret to cash.Value = nil
for the first time the a key is used, which will cause unpredictable behavior - from halting, etc..
so here's how you should do it:
local Players = game:GetService("Players"); local DataStoreService = game:GetService("DataStoreService"); local Datastore = DataStoreService:GetDataStore("MyDataStore"); Players.PlayerAdded:Connect(function(player) local leaderstats = Instance.new("Folder", player); leaderstats.Name - "leaderstats"; local cash = instance.new("IntValue", leaderstats); cash.Name = "Cash"; local data = nil; local s, e = pcall(function() data = Datastore:GetAsync(player.UserId.."-cash") end) if(s) then print("data successfully loaded")' data = data or 0 --this is most important; if no data has been saved, replaces it with 0 for default cash.Value = data else warn("There was a problem loading data:", e); end end); Players.PlayerRemoving:Connect(function(player) local leaderstats = player.leaderstats local cash = leaderstats.Cash local s, e = pcall(function() Datastore:SetAsync(player.UserId.."-cash", cash.Value) end); if(s) then print("data successfully saved"); else warn("There was a problem saving data:", e); end end)
I recommend using datastore2, datastoreservice is pretty broken. Look at this youtube link here: https://www.youtube.com/watch?v=FZx0fVqgRIE