Not sure how to change state of boolean after timer finishes

Godot Version

if Input.is_action_just_pressed("shoot") and can_shoot:
	print('shoot')
	can_shoot = false	
	var timer : Timer = Timer.new()
	add_child(timer)
	timer.one_shot = true
	timer.autostart = false
	timer.wait_time = 0.6
	timer.timeout.connect(_timer_timeout())	
	timer.start()
	can_shoot = true

Question

I am trying to create a timer that stops the player from spaming the shoot func but I am not sure how to connect the can_shoot = true to the timer being done.

It would be better to add a child timer node once, then get it using the $ operator or get_node. Then you can connect to it’s timeout signal in the editor as well.

A final sample would look something like this.

func _input(event: InputEvent) -> void:
	if Input.is_action_just_pressed("shoot") and can_shoot:
		print('shoot')
		can_shoot = false
		$Timer.start()

func _on_timer_timeout() -> void:
	can_shoot = true

Another option, which you should be aware of, but I don’t think is the best solution is using await with create_timer, which is better for one-off time outs. Keyword await halts the current function call until a signal is emitted, such as timeout.

if Input.is_action_just_pressed("shoot") and can_shoot:
	print('shoot')
	can_shoot = false
	await get_tree().create_timer(0.6).timeout
	can_shoot = true

I did try to use the child timer node but it would crash everytime I called the $ operator because the node did not exist in the remote. I am using the code form because I could not find a way to fix that problem.

In that case await get_tree().create_timer(0.6).timeout seems like the best option. The project can crash if it hot reloads a script with an active await (source) and clashes with pause but I don’t see a reason not to use it here.

1 Like

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