Created
December 29, 2024 21:13
BubuTheDev’s Simple DataStore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--BubuTheDev’s Simple DataStore | |
--Saves player’s leaderstats when leaves or disconnected | |
--Loads and sets the leaderstats when joining the game. | |
local Players = game:GetService("Players") | |
local DataStoreService = game:GetService("DataStoreService") | |
local SAVE_NAME = "LeaderstatsData" --changing it will change data (can be used for testing purposes) | |
local Data = DataStoreService:GetDataStore(SAVE_NAME) | |
function Save(player) | |
local data = {} | |
local leaderstats = player:FindFirstChild("leaderstats") | |
if leaderstats then | |
for _, x in pairs(leaderstats:GetChildren()) do | |
if x:IsA("ValueBase") then | |
data[x.Name] = x.Value | |
end | |
end | |
local success, errormessage = pcall(function() | |
Data:SetAsync(player.UserId, data) | |
end) | |
if not success then | |
error(errormessage) | |
end | |
end | |
end | |
Players.PlayerAdded:Connect(function(player) | |
local data = nil | |
local success, _ = pcall(function() | |
data = Data:GetAsync(player.UserId) | |
end) | |
if success then | |
if data then | |
for i, x in data do | |
local leaderstats = player:WaitForChild("leaderstats") | |
if leaderstats and leaderstats:FindFirstChild(i) then | |
leaderstats:FindFirstChild(i).Value = x | |
end | |
end | |
end | |
end | |
end) | |
Players.PlayerRemoving:Connect(function(player) | |
Save(player) | |
end) | |
game:BindToClose(function() | |
for _, player in pairs(Players:GetPlayers()) do | |
Save(player) | |
end | |
end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment