How to make a code run only once?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By 20xxdd20
if speed == 100:
	print("hello world!")
	$Timer.start()

I have this code which checks if the player’s speed is 100 and if yes, it prints hello world! and starts a timer. But the script runs numerous times but I want it to print only once.

:bust_in_silhouette: Reply From: Wurzelpilz

Make sure your time is set on one shot and create a boolean

if speed == 100 and timerSwitch:
	timer.start()
	timerSwitch = false

I created variables called:

onready var timer = $Timer

var timerSwitch : bool = true

Hello world will still be called multiple times, depending on how much you set your timer. To perform it only once, my code example but without timers, only the boolean.

:bust_in_silhouette: Reply From: sunAson

Use a Boolean variable

onready var only_once : bool = true

if speed == 100 && only_once:
    print("hello world!")
    $Timer.start()
    only_once = false
:bust_in_silhouette: Reply From: uniquegamesofficial

Your code must not be in a function with delta
Example:

func _process(delta):
   if speed == 100:
         print("hello world!")
         $Timer.start()

DO NOT USE delta