local DataStoreService = game:GetService("DataStoreService")
local MissionDataStore = DataStoreService:GetDataStore("MissionDataStore")
local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local MissionComplate = Instance.new("IntValue")
MissionComplate.Name = "MissionComplate"
MissionComplate.Parent = leaderstats
MissionComplate.Value = 0
local data
local success, errormessage = pcall(function()
data = MissionDataStore:GetAsync(player.UserId.."-Mission")
end)
if success then
print("DID")
MissionComplate.Value = data
else
print("ERROR")
warn(errormessage)
end
MissionComplate.Value = MissionComplate.Value + 1 -- this for test
end)
game.Players.PlayerRemoving:Connect(function(plr)
local success, errormessage = pcall(function()
MissionDataStore:SetAsync(plr.UserId.."-Mission",plr.leaderstats.MissionComplate.Value)
end)
if success then
print("SAVED")
else
print("ERROR")
warn(errormessage)
end
end)
Instead of the PlayerRemoving function, try this:
You need a BindToClose function for the saving to work in Studio I believe
You don’t need BindToClose
Try this script:
local DataStoreService = game:GetService("DataStoreService")
local MissionDataStore = DataStoreService:GetDataStore("MissionDataStore")
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local MissionComplate = Instance.new("IntValue")
MissionComplate.Name = "MissionComplate"
MissionComplate.Parent = leaderstats
local data
local success, errormessage = pcall(function()
data = MissionDataStore:GetAsync(player.UserId.."-Mission")
end)
if success then
print("DID")
if data ~= nil then
MissionComplate.Value = data
else
MissonComplate.Value = 0
end
else
MissonComplate.Value = 0
print("ERROR")
warn(errormessage)
end
MissionComplate.Value += 1 -- this for test
end)
Players.PlayerRemoving:Connect(function(plr)
local Data = plr.leaderstats.MissionComplate.Value
local success, errormessage = pcall(function()
MissionDataStore:SetAsync(plr.UserId.."-Mission", Data)
end)
if success then
print("SAVED")
else
print("ERROR")
warn(errormessage)
end
end)
Why wouldnt he have a BindToClose
though?
Edit: to explain a bit, the BindToClose
event fires whenever the game’s server closes. If there are multiple players in the game, it would not save their data if the server were to close for whatever reason. Using a BindToClose
will execute the code inside before closing the server, which in this case saves the player’s data, which in theory guarantees their data saves.
You don’t necessarily need it for it to work.
Well it’s true that data will not save in studio most times without a BindToClose
. In the actual game it’s not as needed but you still should 100% have a BindToClose
set up to save data before the server closes.