Last active
September 12, 2022 05:07
-
-
Save Shilo/3cf2b9f3fb504d46a32572100be58a90 to your computer and use it in GitHub Desktop.
Dynamic persistent leaderstats via DataStore. (ModuleScript in Roblox Studio).
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
local DataStoreService = game:GetService("DataStoreService") | |
local leaderstatsDataStore = DataStoreService:GetDataStore("Leaderstats") | |
local Self = {} | |
function Self.add(player) | |
local success, leaderstatsData = pcall(function() | |
return leaderstatsDataStore:GetAsync(player.UserId) | |
end) | |
if not success then | |
warn(leaderstatsData) | |
return | |
end | |
for name, value in leaderstatsData do | |
local leaderstat = player.leaderstats:FindFirstChild(name) | |
if not leaderstat then continue end | |
leaderstat.Value = value | |
end | |
end | |
function Self.remove(player) | |
local success, errorMessage = pcall(function() | |
local leaderstatsData = {} | |
for _, leaderstat in player.leaderstats:GetChildren() do | |
leaderstatsData[leaderstat.Name] = leaderstat.Value | |
end | |
leaderstatsDataStore:SetAsync(player.UserId, leaderstatsData) | |
end) | |
if not success then | |
warn(errorMessage) | |
end | |
end | |
game:BindToClose(function() | |
for _, player in game.Players:GetPlayers() do | |
Self.remove(player) | |
end | |
if game:GetService("RunService"):IsStudio() then | |
task.wait(1) | |
end | |
end) | |
return Self |
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
local ChildrenManager = require(script.ChildrenManager) | |
local LeaderstatsDataStoreManager = require(script.LeaderstatsDataStoreManager) | |
game.Players.PlayerAdded:Connect(function(player) | |
ChildrenManager.new(player) | |
LeaderstatsDataStoreManager.add(player) | |
end) | |
game.Players.PlayerRemoving:Connect(function(player) | |
LeaderstatsDataStoreManager.remove(player) | |
end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment