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


local Players = game:GetService("Players")

local MAX_TOOLS = 4

local function countTools(player)
	local count = 0

	local backpack = player:FindFirstChild("Backpack")
	if backpack then
		for _, item in ipairs(backpack:GetChildren()) do
			if item:IsA("Tool") then
				count += 1
			end
		end
	end

	local character = player.Character
	if character then
		for _, item in ipairs(character:GetChildren()) do
			if item:IsA("Tool") then
				count += 1
			end
		end
	end

	return count
end

local function enforceLimit(player)
	local backpack = player:FindFirstChild("Backpack")
	if not backpack then return end

	-- если больше лимита, удаляем лишние (последние добавленные)
	local tools = {}
	for _, item in ipairs(backpack:GetChildren()) do
		if item:IsA("Tool") then
			table.insert(tools, item)
		end
	end

	while #tools > MAX_TOOLS do
		local tool = tools[#tools]
		if tool then
			tool:Destroy()
		end
		table.remove(tools, #tools)
	end
end

local function setupPlayer(player)
	local backpack = player:WaitForChild("Backpack")

	backpack.ChildAdded:Connect(function(child)
		if child:IsA("Tool") then
			-- учитываем и tool в руке
			if countTools(player) > MAX_TOOLS then
				child:Destroy() -- лишний предмет не добавляем
			end
		end
	end)

	player.CharacterAdded:Connect(function(character)
		character.ChildAdded:Connect(function(child)
			if child:IsA("Tool") then
				if countTools(player) > MAX_TOOLS then
					child.Parent = backpack
					enforceLimit(player)
				end
			end
		end)
	end)

	enforceLimit(player)
end

Players.PlayerAdded:Connect(setupPlayer)
for _, player in ipairs(Players:GetPlayers()) do
	setupPlayer(player)
end