How do I connect signals via code in Godot 4.2?

Godot Version

Using Godot 4.2


extends Area2D

@export var next_level : PackedScene

func _ready():
	print("Door active.")

func _on_body_entered(body):
	if body is CharacterBody2D:  # Check if the body is a CharacterBody2D
		print("inside body.")

Basically, I’m just not very smart and reading the docs and seeing examples didn’t help me, so here I am.

I want to make an area2D transfer the player from one level to the next… eventually. For now, I’m just trying to get it to print the statement when the player is inside the area. I know how to connect the signal in the editor, and it works fine doing it that way and prints the statement.

However, I cant figure out how to connect the signal from code.

the connect parameter should be a callable, either a lambda or a just function/method name

ok so it’s from area2d…
to connect from script, use


no it doesn’t. the script above goes onto an area 2D, and then, how I’ve gotten it to work in the editor is, I connect the body_entered signal to the area2D itself.

I cant seem to replicate this in code though.

ah ye, sorry i edited now, i misread it

ty for the quick reply.

that did the trick!

1 Like

no problem, mind that it works because the parameter from signal and target function is the same, both take 1 argument/parameter and same type, but what happened if you want to connect to a function with 2 arguments or take none with only signal that only has 1 argument to load?
you can use the lambda function:
.connect(func(parameter1): target_method(parameter1, other parameter))

.connect(func(parameter1): target_method_with_no_parameter())

for your code
this will also works
self.body_entered.connect(func(the_body): _on_body_entered(the_body))

Honestly it didn’t really occur to me that connecting the signal using a function that took 2 arguments when it only needed 1, were different type(s) from the one the signal needed, or through connecting a function with 0 arguments could still even work correctly.

Why would someone choose to do this? I’m sure it’s useful - I’m just having trouble understanding why.

when a child sending a signal to a parent (since using get_parent() is a bad practice from what i read) or when a node needed to broadcast a signal to whole node about something, it will come useful

notice that the signal is a built-in signal made for Area2d node, you also can create a custom signal depending on what you need

Also, take a look at Global EventBus for simpler signaling:,Global%20Event%20Bus,-In%20GoDot%20we

1 Like

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