Money save doesn't work for some reason

My money won’t save when I join my game again… no there are no errors popping in the output

script:

local DataStore = game:GetService("DataStoreService"):GetDataStore("PlayerStats")

function playerAdded(plr)

	local stats = Instance.new("StringValue");
	stats.Parent = plr;
	stats.Name = "leaderstats";

	local cash = Instance.new("IntValue");
	cash.Parent = stats;
	cash.Name = "Money";

	local usr = "user_" .. plr.userId;

	DataStore:UpdateAsync(usr, function(oldValue)

		local theNewValueYouWant = 0;

		if (oldValue ~= nil) then
			theNewValueYouWant = 0;
		end

		return theNewValueYouWant;
	end)	

	cash.Value = DataStore:GetAsync(usr);
end

game.Players.PlayerAdded:connect(playerAdded);
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("DataStoreValues") --Name the DataStore whatever you want

game.Players.PlayerAdded:Connect(function(player)

    local leaderstats = Instance.new("Folder", player)
    leaderstats.Name = "leaderstats"

	local Money = Instance.new('NumberValue', leaderstats)
	Money.Name = "Money"
	Money.Value = 0

	local value1Data = Money

	local s, e = pcall(function()
		value1Data = DataStore:GetAsync(player.UserId.."-Value1") or 0 --check if they have data, if not it'll be "0"
	end)

	if s then
		Money.Value = value1Data --setting data if its success
	else
		game:GetService("TestService"):Error(e)  --if not success then we error it to the console
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
local s, e = pcall(function()
	DataStore:SetAsync(player.UserId.."-Value1", player.leaderstats.Money.Value) --setting data
	end)
	if not s then game:GetService("TestService"):Error(e) 
	end
end)

Try this script.

local DSService = game:GetService("DataStoreService")
local PlayerStats = DSService:GetDataStore("PlayerStats")
local players = game:GetService("Players")

players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Parent = player
	leaderstats.Name = "leaderstats"

	local cash = Instance.new("IntValue")
	cash.Name = "Money"
	cash.Parent = leaderstats
	cash.Value = nil

	local key = "User_" .. player.UserId
	local res = PlayerStats:GetAsync(key)
	if type(res) == "number" then
		cash.Value = res
	else
		cash.Value = 0
	end
	player.CharacterAdded:Connect(function(character)
		local res = PlayerStats:SetAsync(key, cash.Value)
	end)
end)

Here you go, I’ve just tested this in studio and it works. When the player joins it either loads their current cash stat from the DataStore (or 0 if they haven’t been stored in the DataStore yet) and then each time the player’s character respawns their cash stat is saved to the DataStore.

Why would cash value be nil though?
Couldn’t it be set to 0 or another number just in case they want starter money?

It later gets set to 0 if they don’t have an existing value saved in the DataStore.

1 Like

I see. Thanks for the clarification.