Afk = false local Button = script.Parent function onClick() print("Clicked") Afk = not Afk print(Afk) end if Afk == true then Button.Text = "Afk is On" print("Afk is on") end if Afk == false then Button.Text = "Afk is Off" print("Afk is off") end Button.MouseButton1Click:connect(onClick)
This is my code, what its supposed to do is when the Gui button is clicked is toggles the value Afk to its opposite and then prints what the current status of Afk is, and depending on what the value is it will change the text of a gui button and print whether afk is on or not, but when i click the button it shows the status and yes it does print it toggling back and forth, so i know the value is changing, but the if statements arent running. I would really appreciate if someone could help me figure out why.
The issue is that your if statements are outside of your function
. Meaning the if statements will only execute once. You should move them inside of your function
so that they will execute along with the other code.
local Afk = false local Button = script.Parent local function onClick() print("Clicked") Afk = not Afk print(Afk) if Afk then -- == true not needed Button.Text = "Afk is On" print("Afk is on") else: -- if Afk is FALSE Button.Text = "Afk is Off" print("Afk is off") end end Button.Activated:Connect(onClick)
It is also recommended that you localise your variables
and indent your code
for the sake of readability. You should also use Activated
rather than MouseButton1Click
since according to this post by a staff member, the latter will eventually be deprecated, and finally, :connect()
is deprecated, use :Connect()
/
Afk = false local Button = script.Parent function onClick() print("Clicked") Afk = not Afk print(Afk) end if Afk == true then Button.Text = "Afk is On" print("Afk is on") end if Afk == false then Button.Text = "Afk is Off" print("Afl is off") end Button.MouseButton1Click:connect(onClick)
here is the code in the correct format hopefully
Your text doesn't change because it is not put inside the clicked event. It is going to run the check once, and that is at the start of the game. You just need to check for the AFK value inside the clicked event. Also, it's recommended to use local variables as they can be accessed faster.
--Use local variables. local Afk = false local Button = script.Parent function onClick() print("Clicked") Afk = not Afk print(Afk) --check for AFK value inside onClick if Afk == true then Button.Text = "Afk is On" print("Afk is on") else Button.Text = "Afk is Off" end end --:connect is deprecated, use :Connect Button.MouseButton1Click:Connect(onClick)