Are there any memory leaks?

I don’t know much about how Gui behaves and when i should disconnect event or is there any more performant way, this code below is Main controller of Inventory System, it listens to events and controls modules

local player = game:GetService("Players").LocalPlayer

-- Services
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Modules
local Render = require(script.Render)

-- Important 
local Inventory = ReplicatedStorage.Inventories:WaitForChild(player.UserId)
local Weight = Inventory.Backpack.Weight
local MaxWeight = Inventory.Backpack.MaxWeight
-- Which parts of inventory should be displayed
local FoldersToDisplay = {
	["Inventory"] = 1,
	["SingleItems"] = 1
}

-- Clear inventory frames and clear frame's list
local function ClearInventory()
	for Item, Frame in Render.Displayed do
		Render.Displayed[Item] = nil
		Frame:Destroy()
	end
end

-- Creates new item frame and also listens if item was dropped or changed soo it can update weight bar or stop displaying frame
local function NewItem(Item: ValueBase)
	local NewFrame = Render:CreateItemFrame(Item)
	Render.Displayed[Item] = NewFrame
	Render:UpdateWeightBarSize(Weight.Value, MaxWeight.Value)
	
	-- [[If item is stackable then update frame when value changes, if it's not then destroy frame when tool is dropped]]
	if Item.ClassName == "IntValue" then
		Item.Changed:Connect(function() 
			Render:UpdateItemCount(NewFrame, Item) 
			Render:UpdateWeightBarSize(Weight.Value, MaxWeight.Value)
		end) 
		return
	end
	
	-- [[If item is non-stackable then when it's dropped update weight bar, destroy frame and remove it from frame's list]]
	Item.Destroying:Once(function()
		NewFrame:Destroy()
		Render.Displayed[Item] = nil
		Render:UpdateWeightBarSize(Weight.Value, MaxWeight.Value)
	end)
end

-- Loads inventory when called
local function LoadInventory(state: boolean)
	ClearInventory()

	-- [[Go through folders that should be displayed and call NewItem function to load every item, also listen if any new item was added]]
	for folderName, _ in FoldersToDisplay do
		local Folder = Inventory[folderName]
		for i, Item in Folder:GetChildren() do
			if state then  end
			NewItem(Item)
		end
		
		Folder.ChildAdded:Connect(NewItem)
	end
end

player.CharacterAdded:Connect(LoadInventory)
LoadInventory(true) --/ Load inventory when player joins the game

Nope. I don’t see any tables or variables that needs to be cleared or removed and this event should automatically be disconnected by the garbage collector when the folder is deleted (I’m assuming when the player dies or leave)

So yeah, well done (:

2 Likes

This Folder’s Parent is removed when player leaves, soo yea thx for help

1 Like

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