Загрузка данных


local DataStoreService = game:GetService("DataStoreService")
local CoinStore = DataStoreService:GetDataStore("PlayerCoinsDataStore_v1")

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

	local coins = Instance.new("IntValue")
	coins.Name = "Coins" -- Название вашей валюты
	coins.Value = 0
	coins.Parent = leaderstats

	-- Загрузка данных
	local playerUserId = "Player_" .. player.UserId
	local success, savedCoins = pcall(function()
		return CoinStore:GetAsync(playerUserId)
	end)

	if success and savedCoins then
		coins.Value = savedCoins
	else
		coins.Value = 100 -- Стартовый баланс для новых игроков
	end
end)

-- Сохранение данных при выходе
game.Players.PlayerRemoving:Connect(function(player)
	local playerUserId = "Player_" .. player.UserId
	if player:FindFirstChild("leaderstats") and player.leaderstats:FindFirstChild("Coins") then
		local coinsValue = player.leaderstats.Coins.Value
		pcall(function()
			CoinStore:SetAsync(playerUserId, coinsValue)
		end)
	end
end)

-- Сохранение при закрытии сервера (защита от вылетов)
game:BindToClose(function()
	for _, player in ipairs(game.Players:GetPlayers()) do
		local playerUserId = "Player_" .. player.UserId
		if player:FindFirstChild("leaderstats") and player.leaderstats:FindFirstChild("Coins") then
			local coinsValue = player.leaderstats.Coins.Value
			pcall(function()
				CoinStore:SetAsync(playerUserId, coinsValue)
			end)
		end
	end
end)