user-interfaceluaroblox

GUI-changing Roblox script doesn't change text


I have the following script that's meant to change the text on a TextButton when it's clicked:

game.StarterGui.ScreenGui.TextButton.MouseButton1Click:Connect(function()       
        game.StarterGui.ScreenGui.TextButton.Text = "Clicked"
        wait(1)
        game.StarterGui.ScreenGui.TextButton.Text = "CLICK ME."
end)

It's not actually changing the text when I click the button. How can I make it work?


Solution

  • Your issue here is you are using a script underneath Workspace instead of under StarterGui.

    You will notice when you test a game that all of the items under StarterGui get copied to the Player objects in "Players"; modifying the StarterGui version won't change the individual players' copies. You need to move this script inside of the ScreenGui and reference the copy of the button as follows:

    -- Parent object
    local screenUI = script.Parent
    
    screenUI.TextButton.MouseButton1Click:Connect(function()       
        screenUI.TextButton.Text = "Clicked"
        wait(1)
        screenUI.TextButton.Text = "CLICK ME."
    end)