Skip to content

Instantly share code, notes, and snippets.

@BrastenXBL
Created January 26, 2025 04:58
Show Gist options
  • Save BrastenXBL/689bc90e3e69a9d16e56650f8d35e869 to your computer and use it in GitHub Desktop.
Save BrastenXBL/689bc90e3e69a9d16e56650f8d35e869 to your computer and use it in GitHub Desktop.
A simple timed spawner for Godot 4.3 3D
class_name TimedSpawner3D
extends Marker3D
## Drag the enemy or object .tscn that will be copied, instantiated
@export var spawn_scene : PackedScene
# This is making it easier to customize, and passes through to the Timer node.
## Scene will only spawn once if this is turned on.
@export var one_shot_spawn : bool = false
# This is making it easier to customize, and passes through to the Timer node.
## The time in Seconds between spawns.
@export var spawn_time_delay : float = 5.0
## The maximum number of spawns before this Spawner shuts off. -1 means infinite spawns.
@export var maximum_spawns : int = 5
var timer : Timer
func _ready():
timer = Timer.new()
add_child(timer)
# Check for invalid negative number values.
if spawn_time_delay < 0.0:
spawn_time_delay = 0.01
if maximum_spawns < -1:
maximum_spawns = 0
# Check if there is no .tscn assigned. Checking for a 'null'
if not is_instance_valid(spawn_scene):
push_warning(self.name, " does not have an assigned Spawn Scene .tscn and will remove itself.")
queue_free()
else:
timer.timeout.connect(_on_timer_timeout)
timer.one_shot = one_shot_spawn
timer.wait_time = spawn_time_delay
timer.start()
## The steps to instantiate a copy of PackedScene .tscn, and add it to the SceneTree
func _spawn_scene():
var spawn_instance = spawn_scene.instantiate()
get_tree().root.add_child(spawn_instance,true)
spawn_instance.global_position = self.global_position
# use PackedScene.instantiate() to create new Nodes, from the blueprint stored in the .tscn
# Get the 'root' game Window node from SceneTree, and add this new Node as a child
# using add_child(spawn_instance, force_readable_name = true).
# Set the new Node's position to be the same as the "self" global_position of this Marker3D node.
# This new Node will not be a child of this Marker3D.
func _on_timer_timeout():
if maximum_spawns > 0:
maximum_spawns -= 1
_spawn_scene()
elif maximum_spawns == 0:
timer.stop()
else:
_spawn_scene()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment