While Loop, Timers and Spawning Help

Godot Version - 4.3

What im trying to do: Start timer (45.0) >>> do stuff - animation open >>> stop doing stuff >>> end with animation closed
Stop everything after 45 second timer has run out.

func start_spawning_mailpackages() -> void:
	#timer for total func runtime
	var time_limit_timer = get_tree().create_timer(45.0)
	#waits 5 secs
	await get_tree().create_timer(package_begin_timer).timeout
	#animation opens takes 4 secs
	factory_entrance_anim.play("door_open")
	#wait for animation to finish
	await factory_entrance_anim.animation_finished
	#wait 1 sec to start spawning
	await get_tree().create_timer(1.0).timeout
	
	# get mail container for appending child nodes
	var mail_container: Node2D = get_parent().get_node("MailContainer")
	
		#while current package count is less than 5 keep spawning
		while current_package_count < MAX_PACKAGES_IN_AREA:
			#spawn package logic 
			spawn_package(mail_container)
			#wait 3 secs per spawn
			await get_tree().create_timer(spawn_delay_time).timeout
			
			if time_limit_timer.time_left <= 0:
				break
	#animation close takes 4 secs
	factory_entrance_anim.play("door_close")

Issues:
Timer runs out animation close finished but while loop ignored which keeps spawning.
Animation just opens and closes in a loop.
Func does not stop even though it is only run in Ready.

Hope the comments are helpful as im try to rubber duck it.
Is this even a good approach or am I best going a different way?

Edit1:

if time_limit_timer.time_left <= 0:
				break

Just noticed this is causing the while loop to be ignored. Not sure if a move that out of the loop it would make a difference…

There’s a lot of ambiguity in your writing “Start timer (45.0) >>> do stuff - animation open >>> stop doing stuff >>> end with animation closed”
but judging from the code here’s some preliminary advice:
Move things into separate functions:

  • Function to ready the nodes you need
  • Function to create a package
  • Function called when an animation is over
  • Function called when time is up on the timer
    Then keep track of what is going on with a state enum like:
    enum STATE{
    NONE,
    OPENING,
    SPAWNING,
    CLOSING
    }
    Using a simple enum like that in the functions can help provide clarity and hey, who doesn’t love clarity?
1 Like

I did have a number of things seperated but tried to condense this one with three other func. Thought I was being smart be guess not.

Will start spliting this up and use the enum idea. Seems solid. Cheers