Cannot connect signal from area 2d node

Godot Version

Question

I have 2 scripts; boss and a state. The boss has a reference to an area2d in it’s hierarchy, and I want to to connect the body entered signal to a method in the state script.

Running the project, I get this error;
Invalid get index ‘body_entered’ (on base: ‘Nil’).

heres the line of code (at the top)

godot error

Object._init() is the constructor of the class, at that point the node has not been added to the scene. You can only access nodes once they are added to the scene and are ready. You’ll need to wait for when it’s ready to be able to connect the signal.

Something like this should work:

func _init(boss: Captain) -> void:
	super._init(boss)
	
	# Wait for the node to be ready if it's not
	if not boss.is_node_ready():
		await boss.ready
	
	boss.sightArea.body_entered.connect(on_body_entered)

1 Like

Hello mrcdk,
yes, that solved the problem right away, thank you for your response.

Fortunately, your response helped me find a better way, which is just to use @onready on the var that declares it in the boss class, so that the init func in the state class is called only when the node is ready.

Thank you for your help
Godot solution

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.