Datastore removing and adding money

So my datastore isn’t working, well it is but it’s either adding or taking money every time I join.
Here’s my script so people can see:

game.Players.PlayerAdded:Connect(function(Player)
	local Stats = Instance.new("Folder")
	Stats.Parent = p
	Stats.Name = "Stats"
	
	local Char = Instance.new("Folder")
	Char.Parent = p
	Char.Name = "CharSettings"
	
	local Cash = Instance.new("IntValue")
	Cash.Parent = Stats
	Cash.Name = "Cash"
end)
game.Players.PlayerRemoving:connect(function(Player)
    local DataStore = game:GetService("DataStoreService"):GetDataStore(Player.Name.."Stats")
	local StatsStorage = Player:FindFirstChild("Stats"):GetChildren()
	print("Saving game...")
	for i =  1, #StatsStorage do
		DataStore:SetAsync(StatsStorage[i].Name, StatsStorage[i].Value)
		--DataStore:RemoveAsync(StatsStorage[i].Name, StatsStorage[i].Value)
	end
end)
game.Players.PlayerAdded:connect(function(Player)
    local DataStore = game:GetService("DataStoreService"):GetDataStore(Player.Name.."Stats")
	Player:WaitForChild("Stats")
    wait(1)
    local Stats = Player:FindFirstChild("Stats"):GetChildren()
    for i = 1, #Stats do
    	Stats[i].Value = DataStore:GetAsync(Stats[i].Name)
    end
end)

If anyone knows why please help.

1 Like

Are there any errors in the output?

no. 30 characters

You should try to use Pcalls to easily find out what the errors are.

Without a bind to close function, you will need to test this out in a real game, as studio is infamous for closing faster than the playerremoving can account for. Or just simply add a bind to close function in the script.