How do I toggle a bool variable?

Godot Version

v4.2.2.stable.official [15073afe3]

Question

I’m working on an FPS game and making a flashlight thing. I’m trying to make it so that when the player presses F it toggles the flashlight. Here is my code so far:

extends SpotLight3D

@export var light_on = true

func _process(delta):
	if Input.is_action_just_pressed("toggle light") and light_on == true:
		light_on == false
		visible == false
		
	if Input.is_action_just_pressed("toggle light") and light_on == false:
		light_on == true
		visible == true

I should note that I’m using an FPS controller from the asset store because I’m still a beginner, but the script and the SpotLight3D are something I added.

Your script is using two equal signs here, this will compare the variables to false/true, which does nothing, you might notice a warning telling you “statement has no effect” about such lines.

If you change this to a single equals sign for assignment it will work, but there is a better way.

func _input(event: InputEvent) -> void: # and use _input instead
	if event.is_action_pressed("toggle light") and light_on == true:
		light_on = false
		visible = false
		
	if event.is_action_pressed("toggle light")  and light_on == false:
		light_on = true
		visible = true

not will flip a boolean value. Also useful in if statements like if not is_on_floor(): is used to detect air bourne characters

func _input(event: InputEvent) -> void:
	if event.is_action_pressed("toggle light"):
		light_on = not light_on
		visible = not visible
2 Likes

I ended up using the last example you gave. There is still a lot for me to learn. Thanks for your help!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.