Hello. I have an issue - when i try to save a data with datastore, it wont work. Code ends at :SetAsync function (when i tested it print just stopped at :SetAsync at pcall). Any help is great for me!
local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local database = dataStoreService:GetDataStore("data")
local sessionData = {}
function PlayerAdded(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local dollars = Instance.new("IntValue")
dollars.Name = "Dollars"
dollars.Parent = leaderstats
local success = nil
local playerData = nil
local attempt = 1
repeat
success, playerData = pcall(function()
return database:GetAsync(player.UserId)
end)
attempt += 1
if not success then
warn(playerData)
task.wait(3)
end
until success or attempt == 5
if success then
print("Connected to database")
if not playerData then
print("Assigning default data")
playerData = {
["Dollars"] = 15,
["Cars"] = {"Ferrari", "Bugatti"}
}
end
sessionData[player.UserId] = playerData
else
warn("Unable for get data for", player.UserId)
player:Kick("There is an error while loading your data. Rejoin soon")
end
dollars.Value = sessionData[player.UserId].Dollars
dollars.Changed:Connect(function()
sessionData[player.UserId].Dollars = dollars.Value
end)
end
players.PlayerAdded:Connect(PlayerAdded)
function PlayerLeaving(player)
print(sessionData)
if sessionData[player.UserId] then
local success = nil
local errorMsg = nil
local attempt = 1
print(attempt)
repeat
success, errorMsg = pcall(function()
database:SetAsync(player.UserId, sessionData[player.UserId])
end)
attempt += 1
warn("Errors while saving: "..errorMsg)
if not success then
warn(errorMsg)
task.wait(3)
else
--print("DDHSHODD")
end
until success or attempt == 5
print("Good")
if success then
print("Data saved successfully for ", player.Name)
else
print("Unable to save data for", player.Name)
end
end
end
players.PlayerRemoving:Connect(PlayerLeaving)
function ServerShutdown()
print("Server shutting down...")
for i,player in ipairs(players:GetPlayers()) do
task.spawn(function()
PlayerLeaving(player)
end)
end
end
game:BindToClose(ServerShutdown)