I started learning Datastoreservice… I followed Alvin’s tutorial
local datastoreservice = game:GetService("DataStoreService")
local MyDataStore = datastoreservice:GetDataStore("MyDataStore")
game.Players.PlayerAdded:Connect(function(plr)
local leaderboard = Instance.new("Folder")
leaderboard.Parent = plr
leaderboard.Name = "leaderstats"
local cash = Instance.new("IntValue")
cash.Parent = leaderboard
cash.Name = "bux"
local data
local success, erroronmessage = pcall(function()
data = MyDataStore:GetAsync(plr.UserID.."-bux")
end)
if success then
cash.Value = data
else
warn("error")
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
local success, erroronmessage = pcall(function()
MyDataStore:SetAsync(plr.UserID.."-bux", plr.leaderstats.cash.Value)
end)
end)
it gives me error even if I give my self money in the game w/ the console… and rejoin
I didn’t follow Alvin’s tutorial because its just too long while you could’ve done it faster.
local ds = game:GetService("DataStoreService"):GetDataStore("TestDS")
game.Players.PlayerAdded:Connect(function(p)
local ls = Instance.new("BoolValue", p)
ls.Name = "leaderstats"
local c = Instance.new("IntValue",ls)
c.Name = "Cash"
c.Value = ds:GetAsync(p.UserId) or 10
c.Changed:connect(function(val)
ds:SetAsync(p.UserId, c.Value)
end)
end)
For Extra Protection, you could add these to the code.
local ds = game:GetService("DataStoreService"):GetDataStore("TestDS")
game.Players.PlayerAdded:Connect(function(p)
local no = Instance.new("BoolValue",p)--this
no.Name = "DontSave"--this
game.Debris:AddItem(no,1.5)--aand this.
local ls = Instance.new("BoolValue", p)
ls.Name = "leaderstats"
local c = Instance.new("IntValue",ls)
c.Name = "Cash"
c.Value = ds:GetAsync(p.UserId) or 10
c.Changed:connect(function(val)
if p:FindFirstChild("DontSave") == nil then--and this
ds:SetAsync(p.UserId, c.Value)
end--and this
end)
end)
You don’t need this long code. But if you want, you can keep it
local no = Instance.new("BoolValue",p)--this
no.Name = "DontSave"--this
game.Debris:AddItem(no,1.5)--aand this.
if p:FindFirstChild("DontSave") == nil then--and this
ds:SetAsync(p.UserId, c.Value)
end--and this
The lines with --this or --and this
Happy to help!
So they basically add a value to the player with Instance.New() which will be deleted in 1.5 seconds.
and the last 3 lines are checking if they found the value, they wont do SetAsync, otherwise if they dont find the value it will save the amount of Cash.Value.
tbh i could’ve done if not p:FindFirstChild("DontSave") then for better understanding