So thanks to Zenith_lord I now have this script that adds cash to a global leaderboard based on the amount of cash a player has in their leaderstats
while true do for _,Player in pairs(game.Players:GetPlayers()) do CashODS:UpdateAsync(Player.Name, function(oldValue) local newValue = oldValue or 0 newValue = newValue + Player.leaderstats.Stage.Value return newValue end) end
Why is this script repeatedly adding the players leaderstat value to the leaderboard? I only want it to add the leaderstat value when the player earns cash. Help would be much appreciated!
Leaderstat/datastore script:
local Data = game:GetService("DataStoreService"):GetDataStore("CashDataStore") local function Added(Player) local LS = Instance.new("Folder",Player) LS.Name = "leaderstats" local Stage = Instance.new("NumberValue", LS) Stage.Name = "Stage" Stage.Value = Data:SetAsync(Player.UserId, 0) end game.Players.PlayerRemoving:Connect(function(Player) Data:SetAsync(Player.UserId, Player.leaderstats.Stage.Value) end) game.Players.PlayerAdded:Connect(Added)
UpdateAsync(...)
takes a key and a function to change the value. Instead of giving it a function, you gave it the value itself. You should change Player.leaderstats.Cash.Value
to a function that changes the value.
For more info, read this
Also, in terms of your game, you shouldn't get data from leaderstats
. Exploiters can easily modify the leaderstats
values. You should store the values in ServerStorage.
I hope this answered your question.
Thank you Zenith_Lord, I fixed the script, however this script is repeatedly adding the players leaderstat to the leaderboard, how do I prevent this?
while true do for _,Player in pairs(game.Players:GetPlayers()) do CashODS:UpdateAsync(Player.Name, function(oldValue) local newValue = oldValue or 0 newValue = newValue + Player.leaderstats.Cash.Value return newValue