How to detect when a gui has been selected in studio?

So I’m making a plugin and when you press the plugin button, you have to have a gui selected for the plugin to work. I know it has something to do with the service “Selection” but I’m not sure how to use it.

1 Like

Sorry I’m on mobile right now so I can’t give examples, but this should help: Selections

2 Likes

I checked that article already and I don’t understand it that much. I’m not that good with for i, v in pairs, it seems people use that a lot when using the service selection.

1 Like

I can help you more tommorow when I’m on my computer. Basically you can use a for loop to loop through all of the selected objects. In your case, I would check if it :IsA(“GuiObject”). If is then you can run your code.

local Selection = game:GetService("Selection")
 
local function getSelectedObjects()
     for _, object in pairs(Selection:Get()) do --loop through all selected things in the workspace
     	if object:IsA("GuiObject") then --check if that selected thing is a gui object
     		print(object.Name.." Is A Gui Object") --print name
             --code here
         else
             print(object.Name.." Is Not A Gui Object")
     	end
     end
end

Selection.SelectionChanged:Connect(getSelectedObjects) --fires whenever the selected objects fires
2 Likes
local toolbar = plugin:CreateToolbar("Gui Plugin")
local ChangeHistoryService = game:GetService("ChangeHistoryService")


function CreateButton(title, tooltip, icon, _function)
	local Button = toolbar:CreateButton(title, tooltip, icon)
	Button.Click:Connect(function()
		_function(Button)
	end)
end


local Selection = game:GetService("Selection")
local Selectable = {"ScreenGui", "SurfaceGui", "BillboardGui"}
local SelectedGuis = {}
local CanSelectMultiple = false
Selection.SelectionChanged:Connect(function()
	SelectedGuis = {}
	for _, object in pairs(Selection:Get()) do
		if table.find(Selectable, object.ClassName) then
			if not CanSelectMultiple then
				SelectedGuis = {object}
				return
			else
				table.insert(SelectedGuis, object)
			end
		end
	end
end)


CreateButton("Change Gui Name", "Change Gui Name", "", function(Button)
	Button:SetActive(false)
	if #SelectedGuis > 0 then
		for _, Gui in pairs(SelectedGuis) do
			local length = math.random(1, 20)
			local name = ""
			for i = 1, length do
				name = name..string.char(math.random(1,60))
			end
			Gui.Name = name
		end
		ChangeHistoryService:SetWaypoint("Changed gui names")
	else print("Select a gui first.") end
end)
1 Like