What would be the proper way to go about doing this; because I have a feeling this is bad practice.

sidenote: The goal of this script is basically to add a new frame inside a Gui for every weapon in the players backpack. And don't mind all the prints, I tried using them to debug

Edit: I was originally having a problem with this code not working on a server but I've since fixed that issue

local replicatedStorage = game:GetService("ReplicatedStorage")
local equipToolEvent = replicatedStorage:FindFirstChild("EquipToolEvent")
local unequipToolsEvent = replicatedStorage:WaitForChild("UnequipToolsEvent")

local player = game.Players.LocalPlayer
player:WaitForChild("Backpack")
local character = player.Character or player.CharacterAdded:wait()

function updateWeapons(tool)
	wait()
	local weapons = player.PlayerGui.InventoryGui.Inventory.Weapons
	local template = weapons:FindFirstChild("WeaponTemplate")
		
	clearInventory(weapons)
			
	local weaponTable = getWeapons(tool)
		
	for index, weapon in pairs(weaponTable) do
		local weaponFrame = template:Clone()
		if weapon.Values.Equipped.Value then
			weaponFrame.EquipButton.Visible = false
			weaponFrame.UnequipButton.Visible = true
		end
		weaponFrame.Name = weapon.Name
		weaponFrame.WeaponNameLabel.Text = weapon.Name
		weaponFrame.DamageLabel.Text = "Damage: " .. weapon.Values.Damage.Value
		weaponFrame.Position = weaponFrame.Position + UDim2.new(0, 0, 0, (index - 1) * 30)
		weaponFrame.Parent = weapons
		weaponFrame.Visible = true
	end
end

------------------------------------------------------------

function clearInventory(weapons)
	if weapons then
		for _, weapon in pairs(weapons:GetChildren()) do
			if weapon.Name ~= "WeaponTemplate" then
				weapon:Destroy()
			end
			print("cleared inventory")
		end
	else
		print("!weapons clear")
	end
end

------------------------------------------------------------

function getWeapons(tool)
	local backpack = player.Backpack
	if backpack then
		local weaponTable = {}
		if tool then
			print("tool")
			table.insert(weaponTable, tool)
		else
			print("!tool")
		end
		for _, weapon in pairs(backpack:GetChildren()) do
			print("inserting " .. weapon.Name)
			table.insert(weaponTable, weapon)
		end
		return weaponTable
	else
		print("!backpack")
	end
end

------------------------------------------------------------

updateWeapons()
equipToolEvent.OnClientEvent:Connect(function(tool) updateWeapons(tool) end)
unequipToolsEvent.OnClientEvent:Connect(function(tool) updateWeapons(tool) end)

2 comments

0

Welp, I increased the wait() on line 10 to 5 seconds and it's working. Still interested in a more suitable way to do this.

0

I removed the wait() from line 10 and instead added a while loop to wait until #backpack:GetChildren() ~= 0