How do I activate a GUI button through a section of code

I expect this to be a basic/trivial question, but I have a spectate function, and I want that when the players load into the map the spectate function automatically closes.
I want to do this through the code activating the GUI button which would normally manually close the spectate menu.
The code path would be as follows


What would I have to write to actvate the ‘StopButton’ TextButton through the code?
Hope this makes sense


I don’t know how to make it close when you load into the map, but I think I can help you make it close by just disabling the GUI and then if you want to open it again with another button, just change it to enable and disable it
I think this should be a server script in serverscriptservice

local plr = game.Players.LocalPlayer
local PlayerGui = game:GetService("PlayerGui")

--Put the code for the loading into the map here
plr.PlayerGui:WaitForChild("Spectate").Enabled = false

Its probably not the best way but lmk if it works

You cannot activate GUI buttons through scripts but you can just copy the code from the buttons “activated function” and then just run that code.


Thanks for replies everyone, I found an alternative way of fixing it by going into the spectate script itself and setting the camera Subject back to the original player if they are part of the team that is in the map.

1 Like