for some reason the leaderstats value is not the same when it loads into another server
local stat = “DogeCoin” --Change to your stat name
local startamount = 0 --Change to how much points the player will start out with
local DataStore = game:GetService(“DataStoreService”)
local ds = DataStore:GetDataStore(“LeaderStatSave”)
–Don’t worry about the rest of the code, except for line 25.
game.Players.PlayerAdded:connect(function(player)
local leader = Instance.new(“Folder”,player)
leader.Name = “leaderstats”
local Cash = Instance.new(“IntValue”,leader)
Cash.Name = stat
Cash.Value = ds:GetAsync(player.UserId) or startamount
ds:SetAsync(player.UserId, Cash.Value)
Cash.Changed:connect(function()
ds:SetAsync(player.UserId, Cash.Value)
end)
end)
game.Players.PlayerRemoving:connect(function(player)
ds:SetAsync(player.UserId, player.leaderstats.Cash.Value) --Change “Points” to the name of your leaderstat.
end)
Assuming “stat” is a variable, does it store the name “Cash”?
You need to have the IntValue called “Cash” for it to work with your saving script.
Like @Forummer said, ensure the cash value is changed on the server - anything changed on the client only changes for that client (excluding things like setting network ownership).
This is going to overload the data store with requests, eventually. It’s really inefficient.
Save every 5-10 minutes or so, and save on player leaving. Also add a BindToClose() function to save when the game shuts down.
Use a pcall() whenever accessing the DataStore. I’d also recommend using UpdateAsync(), because it allows you to prevent data loss. Even if you don’t put any extra code in for UpdateAsync, it has certain safety features that SetAsync doesn’t.
--loading
local data
local success, result = pcall(function()
data = ds:GetAsync(player.UserId)
end)
if success then
--do stuff because it worked
else
--do stuff because it didn't work. I'd say maybe kick the player if their data didn't load.
end
--saving
local success, result = pcall(function()
ds:UpdateAsync(player.UserId, function(old)
return player.leaderstats.Cash.Value
end)
end)
use BindToClose()
local RunService = game:GetService(“RunService”)
local PlayerService = game:GetService(“Players”)
if not RunService:IsStudio() then
– // Safe with PlayerRemoving
else
game:BindToClose(function()
for _,player in PlayerService:GetPlayers() do
– // Now use the same data-saving function
end
end)
end