✓ Accepted answer
Let's start over with the Services. We only need 1 Service: DatastoreService. and RunService, if you want to.
DatastoreServices is a Roblox Built-in service designed to save player data, it is advised to have a basic understanding of Roblox Lua before operating with DatastoreService since it could be confusing at times. There are a few alternatives to DatastoreService, of course, if you want to be more advanced with your data saving; like Datastore2, ProfileService, etc.
Let's get onto the code:
local Players = game:GetService("Players")
local DSS = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")
local Data = DSS:GetDataStore("CurrencyData")
Players.PlayerAdded:Connect(function(plr)
local Key = plr.UserId.."Data"
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = plr
local Clicks = Instance.new("IntValue")
Clicks.Name = "Clicks"
Clicks.Value = 0
Clicks.Parent = leaderstats
local Rebirths = Instance.new("IntValue")
Rebirths.Name = "Rebirths"
Rebirths.Value = 0
Rebirths.Parent = leaderstats
local Coins = Instance.new("IntValue")
Coins.Name = "Coins"
Coins.Value = 0
Coins.Parent = leaderstats
local Gems = Instance.new("IntValue")
Gems.Name = "Gems"
Gems.Value = 0
Gems.Parent = leaderstats
task.wait()
local Loaded, Value, Error = pcall(function()
return Data:GetAsync(Key)
end)
if Loaded then
if Value then
print("Successfully loaded data")
Clicks.Value = Value[1]
Rebirths.Value = Value[2]
Coins.Value = Value[3]
Gems.Value = Value[4]
end
else
if Error == nil then
print("System failed to load data due to an unknown reason")
else
print("System failed to load data")
warn(Error)
end
end
end)
Players.PlayerRemoving:Connect(function(plr)
local Key = plr.UserId.."Data"
local leaderstats = plr.leaderstats
local Saved, Error = pcall(function()
Data:SetAsync(Key, {leaderstats.Clicks.Value, leaderstats.Rebirths.Value, leaderstats.Coins.Value, leaderstats.Gems.Value})
end)
if Saved then
print("Successfully saved data")
else
print("System failed to save data")
warn(Error)
end
end)
game:BindToClose(function()
if RunService:IsStudio() then return end
local p = Players:GetPlayers()
for _, plr in pairs(p) do
local key = plr.UserId .. "Data"
local leaderstats = plr.leaderstats
local Success, Result = pcall(function()
Data:SetAsync(key, {leaderstats.Clicks.Value, leaderstats.Rebirths.Value, leaderstats.Coins.Value, leaderstats.Gems.Value})
end)
if not Success then
warn(Result)
end
end
end)
3 comments
well thx for trying but it unfortunantly did not work
Make sure you test Datastores in-game and not Studio. PlayerRemoving tend to not work when you're testing in the Studio instead of the game itself.
still did not work