boolean value only works once and then stops

Viewed 108

so im using godot and im trying to set up a button to switch between fullscreen and not, and when i run it and click the button it switches to fullscreen but then it decides to not want to switch back
code below:


extends Button

var on = false

func _on_FullScreen_pressed():
    if on == true:
        on = false
        OS.window_fullscreen = false
        $Label.text = "Fullscreen: No"

    if on == false:
        on = true
        OS.window_fullscreen = true
        $Label.text = "Fullscreen: Yes"

i assume the problem is happening because i set on to false in the top if statement, then in the bottom if statement reads it as false and sets it back
if that is the case please provide me with a way to fix

3 Answers

Change the second if to elif. Or to else and remove the condition

You could use a toggle like this:

 extends Button

var fullscreen = false

func _on_FullScreen_pressed():
    fullscreen = !fullscreen #toggles fullscreen
    OS.window_fullscreen = fullscreen
    if(fullscreen):
        $Label.text = "Fullscreen: Yes"
    else:
        $Label.text = "Fullscreen: No"

or even better, use a toggleable button with the correct event:

extends Button

func _ready():
    set_toggle_mode(1)

func _on_Button_toggled(button_pressed):
    OS.window_fullscreen = button_pressed
    if button_pressed:
        $Label.text = "Fullscreen: Yes"
    else:
        $Label.text = "Fullscreen: Yes"
extends Button

var on = false

func _on_FullScreen_pressed():
    if on == true:
        on = false
        OS.window_fullscreen = false
        $Label.text = "Fullscreen: No"

    else:
        on = true
        OS.window_fullscreen = true
        $Label.text = "Fullscreen: Yes"

Related