✓ Accepted answer
Okay so this data store script is pretty faulty:
- You're not using pcalls, in case data store service is down
- You're using GetAsync for saving data, which is only used to retrieve it
- You're not using BindToClose as well
- You're saving the data store with a non-unique key, it being just the Player.UserId(which works, however if you have multiple data stores they will overwrite data and possibly error your code)
This is how an actual data store setup would look like: (I didn't test it so tell me if something doesn't work)
local DataStoreService = game:GetService("DataStoreService")
local CashDS = DataStoreService:GetDataStore("Cash")
local RS = game:GetService("RunService")
game.Players.PlayerAdded:Connect(function(plr)
local ls = Instance.new("Folder")
ls.Name = "leaderstats"
ls.Parent = plr
local Cash = Instance.new("IntValue")
Cash.Name = "Cash"
Cash.Parent = ls
Cash.Value = 0
local data
local g, err = pcall(function()
data = CashDS:GetAsync("cash_"..plr.UserId)
end)
if not g then
warn(err)
else
if data ~= nil then
Cash.Value = data
end
end
end)
game:BindToClose(function()
if RS:IsStudio() then return end
local plrs = game.Players:GetPlayers()
for _, plr in pairs(plrs) do
local data = plr.leaderstats.Cash.Value
if plr:FindFirstChild("TagValue") then
data -= 50
end
if data then
local g, err = pcall(function()
CashDS:UpdateAsync("cash_"..plr.UserId, function(old)
local new = old or 0
new = data
return new
end)
end)
if not g then
warn(err)
end
end
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
local data = plr.leaderstats.Cash.Value
if plr:FindFirstChild("TagValue") then
data -= 50
end
if data then
local g, err = pcall(function()
CashDS:UpdateAsync("cash_"..plr.UserId, function(old)
local new = old or 0
new = data
return new
end)
end)
if not g then
warn(err)
end
end
end)
I recommend you read up on https://developer.roblox.com/en-us/articles/Data-store as well as you can ask me any questions you could have.
5 comments
Yep I noticed an error real quick, when you create the value add this line under the instancing: Cash.Name = "Cash"
--I edited the code with the name change, as well as making it into a leaderstat. Flag me as answered if this has solved your issue.
Nope, Doesn't work. I wonder why
Yes it does because I tested it, you either don't have API services toggled on in Game Settings under security; Or you're trying to modify and test in studio. If API services are on, join a live game, open the F9 console, switch to server, and paste this in: game.Players.MajinBluee.leaderstats.Cash.Value = 500 - then rejoin.
Oh I was just testing it in studio. Ty