How to add variables to nodes created with code?

Godot Version

4.2.1

Question

Is it possible to add custom variables to Timers that are created in code?

More information

I’m making a Frogger clone and have 6 lanes of traffic where I spawn vehicles.
When the frog gets hit, I want a specific lane to stop spawning vehicles.

I spawn vehicles with a timer. This is the code:

var vehicle_timer: Timer = Timer.new()
add_child(vehicle_timer)
vehicle_timer.autostart = true
vehicle_timer.start(vehicle_time)
vehicle_timer.timeout.connect(func spawn_vehicle():
	spawned_vehicles_array[lane_number] += 1
		
	# Spawn vehicle
	var vehicle_instance = vehicle_type.instantiate()
	vehicle_instance.global_position = spawn_point
	vehicle_instance.speed = vehicle_speed
	vehicle_instance.lane = lane_number
	%Enemies.add_child(vehicle_instance)
		
	# If spawned on the right
	if spawn_point.x > 0:
		vehicle_instance.flip_direction()
	)

As you can see, I have access to the lane_number and I already give it to the vehicle, so that the vehicle can communicate on which lane the accident happened. But I don’t know how to give a Timer that is created with code a custom variable like lane_number.

Even more info and some thoughts

Then again, I created the timers with code, because I thought it should be possible to have more or less lanes of traffic, but since then I am sticking with 6 lanes of traffic.
So I could also create 6 Timer nodes and give them a script.
Oh yeah, it’s possible to add a script to a Timer (or anything) created in code as well, isn’t it? I’ll look into that, but maybe anyone out there has another solution.

Thank you for taking the time.

You could make a custom scene that extends Timer and has a script attached to it that holds a variable for this. But in your case, you could probably also just get away with using set_metadata and get_metadata.

You can bind arguments to the connected function like this:

vehicle_timer.timeout.connect(spawn_vehicle.bind(lane_number))

func spawn_vehicle(lane:int):
	...
1 Like