How do I make inventory/backpack limited?

This is my code:

local limit = 1
local player = game:GetService("Players").LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
repeat wait() until player
repeat wait() until char
local backpack = player.Backpack or player:WaitForChild("Backpack")

function updateTools()
	local BackPackItems = backpack:GetChildren()
	if #BackPackItems > limit then
		for i = limit, #BackPackItems do
			BackPackItems[i]:Destroy()
		end
	end
end

backpack.ChildAdded:Connect(updateTools)
char.ChildAdded:Connect(updateTools)

The code works but it gives me the following warning:

image

I edited the script a bit and it works fine for me, without the error.

local Debris = game:GetService("Debris") --Added this variable

local limit = 1
local player = game:GetService("Players").LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
repeat wait() until player
repeat wait() until char
local backpack = player.Backpack or player:WaitForChild("Backpack")

function updateTools()
	local BackPackItems = backpack:GetChildren()
	if #BackPackItems > limit then
		for i = (limit + 1), #BackPackItems do
			Debris:AddItem(BackPackItems[i], 0) --Replaced "BackPackItems[i]:Destroy()" with this line
		end
	end
end

backpack.ChildAdded:Connect(updateTools)
char.ChildAdded:Connect(updateTools)

I tested my script by running the game with 2 tools on the floor in the workspace that I picked up to run the ChildAdded events.

1 Like

Please do not destroy stuff on client.

2 Likes

Thank you very much for collaborating!
The code works but it deletes the new item or the new child, so the new code is fixed, Thank you again!

Code:

local Debris = game:GetService("Debris")

local limit = 1
local player = game:GetService("Players").LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
repeat wait() until player
repeat wait() until char
local backpack = player.Backpack or player:WaitForChild("Backpack")
local lastItem = nil 

function updateTools()
	local BackPackItems = backpack:GetChildren()
	if #BackPackItems > limit then
		for i = limit, #BackPackItems do
			if lastItem then
				Debris:AddItem(lastItem, 0) 
			end
			lastItem = BackPackItems[i] 
		end
	end
end

backpack.ChildAdded:Connect(updateTools)
char.ChildAdded:Connect(updateTools)


2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.