Why does my Data Store Script Keep Breaking?

hello,
i made a datestore script but for some reason the script only works half the time. i have used this script in the past and it usssually works but i dont know why its not now.
script:
local DataStoreService = game:GetService(“DataStoreService”)

local myDataStore = DataStoreService:GetDataStore(“myDataStore”)

game.Players.PlayerAdded:Connect(function(player)
local Cash = player.LeaderStatistics.Cash
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 whilst getting your data")
	warn(errormessage)
end

end)

game.Players.PlayerRemoving:Connect(function(player)
local success, errormessage = pcall(function()
myDataStore:SetAsync(player.UserId…"-Cash",player.LeaderStatistics.Cash.Value)
end)

if success then
	print("Player Data Was Successfully saved")
else
	print("There was an error when saving")
	warn(errormessage)
end

end)```

You might need this cash script that i use:

local function onPlayerJoin(player)
local leaderstats = Instance.new(‘Folder’)
leaderstats.Name = “LeaderStatistics”
leaderstats.Parent = player

local cash = Instance.new("NumberValue")
cash.Name = "Cash"
cash.Value = 0
cash.Parent = leaderstats

end
game.Players.PlayerAdded:Connect(onPlayerJoin)

This Might Help As Well:


Thank You

i was rejoining and joining the game from roblox from my iphone. sometimes it would save any changes and sometimes it wouldnt. the thing is however, when it doesnt save the data, it deletes all the players cash

To avoid all this, it is better to use the ProfileService or the DataStore2 (I do not know the DataStore v2, since I have not used it). I would recommend using the ProfileService, although it is a bit difficult to use (since it is a ModuleScript and can be confusing), but in the end it works very well. The DataStore2 is also good, it perfectly saves the data but from what I have tested, it does not save the data when you are in the studio.

OK, ill watch a tutorial on profileservice. Is DataStores just Dog Trash?

I have no idea, I am assuming your DataStore does not save or also loses data because it cannot collect it. However, ProfileService works with DataStore. What ProfileService does is it caches the data, and when it exits it just takes the data and saves it so that it is fast and secure.

Everything works correctly. Since you’re using .PlayerRemoving, the function is forced to run after you, the only player in studio, leave the game. Real servers have up to 10 seconds of uptime after the last player leaves. Studio, however, does not.

1 Like