MouseButton1Click Event not firing

Hey there, so I’m basically new to lua and I’m developing a kind-of spawning System for different Items (for example Planes, Cars, etc.). I have a ScreenGui with a ScrollingFrame in it and I’m basically iterating through a Folder and adding Buttons with the Name of the Item. I’m then checking if the Children of the Frame is a button, and if it is, I want to fire the MouseButton1Click event.

For some reason it is not firing.
I tried printing the name of the button but nothing happens.

ModuleScript:

local Spawner = {}

Spawner.location = game.ServerStorage.Items-- Set "Items" to the folder in ServerStorage

return Spawner

Main code:

local configuration = require(game.ServerScriptService.SpawnHandler)
local location = configuration.location	
local frame = game.StarterGui.ScreenGui.ScrollingFrame

local function spawn(item)
	local clone = item:Clone()
	clone.Parent = game.Workspace
end

local function insertButton(scrollingFrame)
	for i, v in pairs(location:GetChildren()) do
		local btn = Instance.new("TextButton")
		btn.Parent = scrollingFrame
		btn.Text = v.Name
		btn.Size = UDim2.new(0, 200,0, 50)
	end
end

insertButton(frame)

for i, v in pairs(frame:GetChildren()) do
	if v:IsA("TextButton") then
		v.MouseButton1Click:Connect(function()
			print(v.Name)
		end)
	end
end

Thanks for any help & solutions

1 Like

StarterGui is only a container for copying Guis to players on spawn, it’s not meant to be interacted with. You should be looking for the Gui under the LocalPlayer’s PlayerGui with a LocalScript.

See: StarterGui / PlayerGui

3 Likes

In addition to this, you don’t need a second loop to connect an event to each button. The MouseButton1Click:Connect function can simply be added in the for loop of the insertButton function like this

local function insertButton(scrollingFrame)
	for i, v in pairs(location:GetChildren()) do
		local btn = Instance.new("TextButton")
		btn.Parent = scrollingFrame
		btn.Text = v.Name
		btn.Size = UDim2.new(0, 200,0, 50)
		btn.MouseButton1Click:Connect(function()
			print(btn.Text)
		end)
	end
end
1 Like