Game crashing. Timer issue?

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

Can someone help a newbie out? My game is crashing after a few shots because of this code. I have a timer node named “shot_timer” set to autostart and 1 second.

func _on_timer_timeout():
var times = [1,2,3]
var shots = 0
var cooldown = rand_range(1,3)

while shots!= times[randi() % times.size()]:
	var laser = scn_laser.instance()
	shots += 1

I have been using yields with one shot timers, but was getting errors and was told to use timers instead. Thought they would be easier to use…

Thanks in advance.

Can you elaborate on your desired behavior? It’s a little hard to tell what you want to do with just your code. while statements have a knack for locking up the app in undesired ways. Sometimes when I write while and that happens, I find that if statements suffice.

DDoop | 2020-07-19 19:53

This code is used to have the enemy ship (in a space shooter game) shoot at slightly random intervals a slightly random number of times.
The “while loop” is there because the function is used only once.
I wonder if I could use if and restart the timer… Gonna try that instead.

Samomba | 2020-07-19 20:19

Thanks for the help. You were extremely helpful.

Samomba | 2020-07-19 20:30

:bust_in_silhouette: Reply From: Samomba

Thank you for the nudge!

All I was doing wrong was using the while loop, when also forgetting to restart the timer after a loop finished.

I have replaced the “while” with an “if” and made sure do “start” the timer again at the end. I wasn’t considering the fact that by refreshing the timer the “if” would trigger over and over again thanks to the “on timeout” function.