I wrote a Datastore script like a month ago, and it was working back then, but now its not working. Please help me, thanks. Script:
local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(player)
local DATAS = Instance.new("Folder")
DATAS.Name = "leaderstats"
DATAS.Parent = player
local Level = Instance.new("IntValue")
Level.Name = "level"
Level.Parent = DATAS
local currexp = Instance.new("IntValue")
currexp.Name = "currentexp"
currexp.Parent = DATAS
local exptolvlup = Instance.new("IntValue")
exptolvlup.Name = "exptolevelup"
exptolvlup.Parent = DATAS
local Beri = Instance.new("IntValue")
Beri.Name = "Beri"
Beri.Parent = DATAS
local playerUserId = "player_"..player.UserId
--Adat betöltése
local data
local success, errormessage = pcall(function()
data = myDataStore:GetAsync(playerUserId)
end)
if success then
if data then
Beri.Value = data.Beri
exptolvlup.Value = data.exptolvlup
currexp.Value = data.currexp
Level.Value = data.Value
end
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = "player"..player.UserId
local data = {
Beri = player.leaderstats.Beri.Value;
Level = player.leaderstats.level.Value;
currexp = player.leaderstats.currentexp.Value;
exptolvlup = player.leaderstats.exptolevelup.Value
}
local success, errormessage = pcall(function()
myDataStore:SetAsync(playerUserId, data)
end)
if success then
print("Data successfully saved!")
else
print("Error!")
warn(errormessage)
end
end)

4 comments
When the last client in the server disconnects it shuts down; Players.PlayerRemoving will not fire. You need to attach a saving callback to game:BindToClose, a method will hold the server open for a maximum of thirty extra seconds to perform any actions you instruct it to via the given callback(s)
https://developer.roblox.com/en-us/api-reference/function/DataModel/BindToClose
Unfortunately, it's still not working.I think it's because I didn't know where to put it.Well, I put this lines of codes to the end of the script, idk if it's good or not..Script: game:BindToClose(function() print(2*2) wait(3) print("Done") end)
You need to include saving logic. Write a local function that will handle saving a player's data, then, iterate through all of the in-game players and call the function on them. You can also use this function as your callback to Players.PlayeRemoving for convenience