I have made a currency, and a system that makes it so it saves when you buy more currency with R$. I have also made a function that subtracts currency when you click a GUI. When I leave the server, it doesn't save the currency I have after I clicked the value subtracting GUI. Here are the two scripts:

This is the script that creates the leaderstats folder and/or gets the data store from the service and loads it into the game.

local currencyName = "Uranium"
local DataStore = game:GetService("DataStoreService"):GetDataStore("TestDataStore") 
game.Players.PlayerAdded:Connect(function(player)

	local folder = Instance.new("Folder")
	folder.Name = "leaderstats"
	folder.Parent = player	
	
	local currency = Instance.new("IntValue")
	currency.Name = currencyName
	currency.Parent = folder
	
	local ID = currencyName.."-"..player.UserId
	local savedData = nil	
	
	pcall(function()
		savedData = DataStore:GetAsync(ID)
	end)
	
	if savedData ~= nil then
		currency.Value = savedData
		print("Data loaded")
	else
		-- New player
		currency.Value = 0
		print("New player to the game")
	end
	
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	local ID = currencyName.."-"..player.UserId
	DataStore:SetAsync(ID,player.leaderstats.Uranium.Value)
end)

game:BindToClose(function()
	for i, player in pairs(game.Players:GetPlayers()) do
		if player then
			player:Kick("Server has closed. Please join again later.")
		end
	end
end)

And this the script that subtracts from the currency:

script.Parent.MouseButton1Click:Connect(function()
	game.Players.LocalPlayer.leaderstats.Uranium.Value = game.Players.LocalPlayer.leaderstats.Uranium.Value - 50
	
end)

Please help! By the way I'm not a very experienced scripter.

5 comments

0

i'm even less experienced than you, but don't you think you can use replicated Storage, or some of the inbuilt things?

0
0

Trust me I've watched that video enough times to grow muscles on my eyes.

0

0_0

0

If that video is from 2016 then it won't work due to FE, when handling data, you MUST use remote events or at least handle data on the server. Changing data on the client won't replicate to the server so basically you are saving the currency of 0 each time you play (assuming you handle adding currency on client too)