I have this script to save Wins and Cash of each player. This script works perfectly fine if it is only saving Win value. However, when I also try to save cash value, it resets everything to 0 instead of saving current value. Can someone please help me?
---------- EDIT----------- After I posted this question, I tried to debug my self by printing. The problem I found is that no matter what I do, the script wont correctly read the value of IntValue. From the commandbar, it prints the correct value but when this script runs it returns 0.
local dataStore = game:GetService("DataStoreService") local playerData = dataStore:GetDataStore("playerData") game.Players.PlayerAdded:Connect(function(player) local leaderStats = Instance.new("Folder") leaderStats.Name = "leaderstats" leaderStats.Parent = player local win = Instance.new("IntValue") win.Name = "Wins" win.Parent = leaderStats local otherData = Instance.new("Folder") otherData.Name = "otherData" otherData.Parent = player local cash = Instance.new("IntValue") cash.Name = "Cash" cash.Parent = otherData local data = nil local success, errorMessage = pcall(function() data = playerData:GetAsync(player.UserId.."-playerData") end) if success then if data then win.Value = data[1] cash.Value = data[2] print("successfully obtained Data") print(data[1].." ".. data[2]) end elseif errorMessage then print("Unseccessfull DataStore") warn(errorMessage) end end) game.Players.PlayerRemoving:Connect(function(player) local wins = player.leaderstats.Wins.Value local cash = player.otherData.Cash.Value local datas = {wins, cash} local success, errorMessage = pcall(function() playerData:SetAsync(player.UserId.."-playerData",datas ) print(datas[1].." ".. datas[2]) end) if success then print("Successed on Saving Data") elseif errorMessage then print("Unsuccessful DataSave") warn(errorMessage) end end)
So the only thing I could say could be causing the problem would be the saving line data store is weird at least from what I have experienced and a simple way to fix this is save your data like this instead
game.Players.PlayerRemoving:Connect(function(player) local wins = player.leaderstats.Wins.Value local cash = player.otherData.Cash.Value local success, errorMessage = pcall(function() playerData:SetAsync(player.UserId.."-playerData",{wins,cash} ) end) if success then print("Successed on Saving Data") elseif errorMessage then print("Unsuccessful DataSave") warn(errorMessage) end end)
I am unsure if that will work for you but that's what I resulted to in the past and seemed to work for me.