Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How Can You Make A Leaderstat Saving System?

Asked by 3 years ago

I've been trying to study on how this datastore system works, I'm still a bit stuck on this saving script. This is what I got.

local DataStore = game:GetService("DataStoreService")


game.Players.PlayerAdded:connect(function(player)
 local leader = Instance.new("Folder",player)
 leader.Name = "leaderstats"
 local Cash = Instance.new("IntValue",leader)
 Cash.Name = "Cash"
 Cash.Value = ds:GetAsync(player.UserId) or 0
 ds:SetAsync(player.UserId, Cash.Value)
 Cash.Changed:connect(function()
  ds:SetAsync(player.UserId, Cash.Value)
end)


game.Players.PlayerRemoving:connect(function(player)
 ds:SetAsync(player.UserId, player.leaderstats.Cash.Value)
end)

It would really be helpful if you could help me :D

1 answer

Log in to vote
2
Answered by 3 years ago
Edited 3 years ago
local DataStore = game:GetService("DataStoreService")
local ds = DataStore:GetDataStore("MyDataStore")

game.Players.PlayerAdded:connect(function(player)
 local leader = Instance.new("Folder",player)
 leader.Name = "leaderstats"
 local Cash = Instance.new("IntValue",leader)
 Cash.Name = "Cash"

local data

local success, errormessage pcall(function()

data = ds:GetAsync(player.UserId.."-cash")
    Cash.Value = data
end)


game.Players.PlayerRemoving:connect(function(player)
local success, errormessage pcall(function()
 ds:SetAsync(player.UserId.."-cash", player.leaderstats.Cash.Value)
    end)
end)

Note: Wrapped It In Pcalls And Made It A Bit Better (This Is The Way I Learned)

Learn More Here: https://developer.roblox.com/en-us/articles/Data-store

0
Thank you, I think Pcalls make it so if the function breaks it won't break the entire script, very helpful! CodedStars 70 — 3y
Ad

Answer this question