How to connect nodes to signal FROM source node?

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

I am making a bullet hell game, I want to be able to programmatically add and subtract bullet spawners. These bullet spawners listen to the parent object to know when to do their on_shoot methods. I am coming from Unity so naturally I tried an observer pattern script first, didn’t work out. Using signals, I can’t figure out how to assign new listeners from the script that emits the signal.

class_name Ship
extends Area2D

# Declare member variables here.
export var gunCount = 0 #number of weapons
export var health = 1 #health points
export var speed = 150.0 #movement speed
export (PackedScene) var Gun #gun prefab
export var guns = [] #list of guns

signal shoot
func bomb():
	pass#bombs
func addGun(PackedScene, GunCount): #adds guns based on count
	for i in range(0,GunCount):
		guns.append(PackedScene)
		print("%d connected" % i)
	for j in range(0,GunCount):
		self.connect("shoot", guns[j], "_On_Shoot")
# Called when the node enters the scene tree for the first time.
func _ready():
	pass

This is my last attempt at trying to achieve this, but it results in an error that reads connect: Parameter "p_to_object" is null.

:bust_in_silhouette: Reply From: yrtv

Why do it in reverse?
Connect signal from Gun to Parent node in Gun's _ready function.

  1. doing it this way just gives me an error that I “attempt to connect to nonexistant signal.” Also worth noting, I’ve instantiated 5 gun scenes, but this error only occurs once.

  2. I’m instantiating the gun in the parent node, so I was making it the same way I’d do an observer script in c#, observer assigns listener, not the other way around. Makes it easier when instantiating tons of listeners.

voodin | 2021-09-30 03:49

I can’t see you instance any gun. guns[j] is null then self.connect("shoot", guns[j], "_On_Shoot") is called. To instance Gun do something like this (depend on your Scene hierarchy plan) add_child(Gun.instance()) then let gun add itself to list of guns in it’s _ready

yrtv | 2021-09-30 12:35