I have a GUI where there are numerous buttons, and when one is pressed, it will fire a RemoteEvent. How can I make it so when any of the buttons are pressed, it will fire the RemoteEvent?
Thank you in advance. I can show screenshots if you need me to.
You can use a for loop and loop through the buttons:
local Buttons = {Button1, Button2}
local Remote = RemoteEvent
for i, v in pairs(Buttons) do
v.Button1Down:Connect(function()
Remote:FireServer()
end)
end
You can for loop it but I wouldn’t recommend wrapping the for loop in a while/repeat loop just to see when the button was pressed. Then again you can always make 1 script and put multiple button events in that script instead of using 1 script per button.
The issue with this is that my buttons are being created via Instance.new. I cannot make a new script and edit it on the fly so this method does not work.
Also @AidanPlaysYT_Real that does not help either. I already know how to use those functions but I’m asking how to check if multiple buttons are pressed.
If you’re creating the buttons using Instance.new() just connect the function to the event after creating it. Example:
local Button = Instance.new("TextButton")
Button.Parent = GUI
Button.MouseButton1Click:Connect(function()
print("Clicked")
end)
If you’re trying to set multiple buttons, create the buttons first and then simply connect them all to the same function, for example:
local Button = Instance.new("TextButton")
Button.Parent = GUI
local Button2 = Instance.new("TextButton")
Button2.Parent = GUI
local Button3 = Instance.new("TextButton")
Button3.Parent = GUI
local function OnClick()
print("Clicked")
end
Button.MouseButton1Click:Connect(OnClick)
Button2.MouseButton1Click:Connect(OnClick)
Button3.MouseButton1Click:Connect(OnClick)
This is useful; however I don’t know how many buttons will be created until the buttons are displayed as it depends on current player count. This means even if I do 5 buttons, if there are 6 players, this function will not work. This is why I do not want to set a finite amount.
local player = game:GetService("Players").LocalPlayer
local Mouse = player:GetMouse()
local PlayerGui = player:WaitForChild("PlayerGui")
function onButton1Down()
local guis = PlayerGui:GetGuiObjectsAtPosition(Mouse.X,Mouse.Y)
print("Button Down on "..guis[1].Name)
end
Mouse.Button1Down:Connect(onButton1Down)