How to make this script work?

if the player clicks a viewportframe’s button it fires an event, but the thing is that it doesn’t work.
the viewport is not instantly added in the gui, but I think this should still have a work around

local inventory = script.Parent
local Equip = game:WaitForChild("ReplicatedStorage"):WaitForChild("Events"):WaitForChild("EquipItem")

for _, v in pairs(inventory:GetChildren()) do
	if v:IsA("ViewportFrame") then
		local name = v.Name
		v:FindFirstChild("Button").MouseButton1Up:Connect(function()
			print("equip")
			Equip:FireServer(name)
		end)
	end
end

You can add a wait() before or use a childAdded event

He did say that the viewport doesn’t load instantly which is the reason this wont work.

The reason is that the viewport doesn’t exist when the script first runs, it gets added later (after the loop finishes) by another script or something

1 Like

It indeed should, waiting for @grandisy to answer now…

Man, I keep forgetting all the roblox functions, I am positive it should work when I try it out in a moment

1 Like

I’d recommend adding repeat wait() until inventory:FindFirstChildOfClass("ViewportFrame") at line 3 to make sure it’s loaded. If there are a specific number of children Inventory is guaranteed to have when loaded, you could make it repeat wait() until inventory:FindFirstChildOfClass("ViewportFrame") and #inventory:GetChildren() == goalNum

Hope this helps!

So? Did it work? If not show me the code you made, I’ll fix it first you.