I am trying to make a datastore system, and I do not have much experience. here is what I have:
local HitStore = DataStoreService:GetDataStore("HitStore")
game.Players.PlayerAdded:Connect(function(Plr)
local Leaderstats = Instance.new("Folder", Plr)
Leaderstats.Name = "leaderstats"
local HitValue = Instance.new("NumberValue", Leaderstats)
HitValue.Name = "Hit's"
local Data
local Success, ErrorMsg = pcall(function()
Data = HitStore:GetAsync(Plr.UserId..".Hits")
end)
if Success then
HitValue.Value = Data
elseif not Success then
print("datastore broken F")
warn(ErrorMsg)
end
end
local SavedPlrs = {}
game.Players.PlayerRemoving:Connect(function(Plr)
local Success, ErrorMsg = pcall(function()
HitStore:SetAsync(Plr.UserId..".Hits", Plr.leaderstats["Hit's"].Value)
end)
if Success then
print("data saved")
table.insert(SavedPlrs, Plr.UserId)
elseif not Success then
print("Data not saved")
warn(ErrorMsg)
end
end)
game:BindToClose(function()
local Players = game.Players:GetPlayers()
for i, v in pairs(Players) do
if not table.find(SavedPlrs, v.UserId) then
local ID = v.UserId
local Success, ErrorMsg = pcall(function()
HitStore:SetAsync(ID..".Hits", v.leaderstats["Hit's"].Value)
end)
if Success then
print("data saved on server shutdown")
elseif not Success then
print("Data not saved on server shutdown")
warn(ErrorMsg)
end
end
end
end)
as I was saying before, a rare glitch can occur where you data does not save/load. I am 75% sure it fails to save, but it could be because of a loading glitch as well. my question is, what am I doing wrong? why does it save successfully most of the time, and output no errors or warnings on the few times it fails?
hopefully someone who is better at datastores then me can help, like I said before I have little experience and do not know why this is happening.