Hello.

I have a main scene "GameScreen" that under certain conditions (on timer or when certain functions are called) emits two signals: declare_day and declare_night respectively.

I want to instance SunPlant scenes that play different animations (flower opening, flower open, flower closing - which is just opening backwards, flower closed) based on whether it's day, night, or whether it has changed.

And I just can't figure out how to make the instance connect to the GameScreen when it's spawned...

extends Node2D

var last_anim = null

func _ready() -> void:
	pass

func _process(delta: float) -> void:
	pass
	
func _on_game_screen_declare_day() -> void:
	$AnimatedSprite2D.play("sun_plant_opening")
	last_anim = "sun_plant_opening"

func _on_game_screen_declare_night() -> void:
	$AnimatedSprite2D.play_backwards("sun_plant_opening")
	last_anim = "sun_plant_closing"
	
func _on_animated_sprite_2d_animation_finished() -> void:
	if last_anim == "sun_plant_opening":
		$AnimatedSprite2D.play("sun_plant_open")
	elif last_anim == "sun_plant_closing":
		$AnimatedSprite2D.play("sun_plant_closed")

Could someone please help me? Connecting signals via the editor when both nodes are on the scene is very easy but I just can't figure out how to make it work through code on instances when the instance should be a passive listener.

I tried looking at several tutorials, text or video, but couldn't transfer the specific examples to my specific example.

  • xyz replied to this.

    ondhan Call connect() on the main scene (or its signal) upon plant instantiation and pass it the signal handler callable that's in the instance.

    You could also use a global object to handle your time and build these signals in as global functions. But that's architecture and not really applicable here I feel.

    If you put all your plant sprites in a group, you can even connect them all at once. You can find it under the signal tab. Godot can handle a LOT of these at ready before the player even sees them. I recommend doing it at ready() vs in the header, because all your sprites don't get enter the tree in order and can cause bugging out.

    func _ready():
       var _plants = get_tree().get_nodes_in_group("plants") 
       for _plant in _plants:
          _plant.connect("on_game_screen_declare_day",GameScreen,"Gamescreen_Declare_Day_orWhatever")

    Thank you both so much. I think in the end I'll go "merely" for a few preplanted plants that the player buys which shows them. That group thing will be particularly useful since their functionality will be identical.

    I realized that instantiating plants would create more issues with moving them around and placing them and for my first actual project I think I will scale back to something I can manage. Still, it's a wonderful experience seeing my stuff actually move and come to life.

    • xyz replied to this.

      ondhan for my first actual project I think I will scale back to something I can manage

      Wise choice 🐱