Adding Timer

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By TitanicJoe

Hi! I’d like add Timer to my tiny project (v3.2.1). Instead of creating node “Timer” and then using comand get_Node(“Timer”) (this code works), I thought i can use timer = Timer.new(). But while running my project jump out error “Timer was not added to the SceneTree”
What am I doing wrong?

extends Node2D

onready var timer = Timer.new()

func _ready():
timer.connect(“timeout”,self,“time_passed”)

func _process(_delta):
tap_counter()

func tap_counter():
if Input.is_action_just_pressed(“click”):
timer.set_wait_time(1)
timer.start()

func time_passed():
print(“wololo”)

:bust_in_silhouette: Reply From: kidscancode

Exactly what the error is saying. A Timer is a node and can’t function if it’s not in the scene tree. You need to add_child() it to the tree - in your _ready() function would be a likely place.

There’s really no advantage to doing it in code like this. Just add a Timer to the scene and be done. Also you don’t need to set the wait time (1 is the default), and you don’t need to start it again, because timers repeat by default. You enable “one shot” if you don’t want that.

:bust_in_silhouette: Reply From: MaaaxiKing

It depends on which position you want the timer to be in the scenetree. If you want it to be a child of your root node and your root node is Node2D and the script is attached to this root node, do add_child(timer) in _ready(). Then it would look like this:

Node2D

Timer