Connecting signal with another scene

Godot Version

4.5

Question

Hi! I’m struggling a bit with connecting a signal to another scene, how do I do that? Here’s my game manager code, note asteroid.connect(“_on_body_entered”, asteroid, 1)

class_name GameManager extends Node


@export var asteroid_scene: PackedScene
@onready var asteroid_timer = $AsteroidTimer

var lives := 0


func _ready() -> void:
	asteroid_timer.start()
	var asteroid = asteroid_scene.instantiate()
	asteroid.connect("_on_body_entered", asteroid, 1)




func _on_asteroid_timer_timeout() -> void:
	var asteroid = asteroid_scene.instantiate()
		
	var asteroid_spawn_location = $AsteroidPath/AsteroidSpawnLocation
	asteroid_spawn_location.progress_ratio = randf()
	
	asteroid.position = asteroid_spawn_location.position
	
	add_child(asteroid)

And here’s my asteroid code:

class_name Asteroid extends RigidBody2D

@export var ground: CollisionShape2D


func _on_body_entered(body: Node) -> void:
	print(body)
	
	if body.typeof(StaticBody2D):
		queue_free()
	
	# TODO: if body is area2d, then bounce, wait few seconds and queue_free()
	# if it is player, then player should take live

_on_body_entered is not a signal. It’s just a method name, so connecting it like this will never work.

The RigidBody2D (the asteroid) emits the built-in signal body_entered, so you should connect that instead:

asteroid.body_entered.connect(asteroid._on_body_entered)

A more cleaner and common way to do this, it’s to handle it inside the asteroid itself, like:

# asteroid.gd
func _ready():
    body_entered.connect(_on_body_entered)
1 Like

I don’t think you need to connect this signal from another scene or code, you should be able to connect body_entered through the editor since both the signal and the function are on the Asteroid.

2 Likes

It doesn’t actually print the body though. Sorry, maybe I’ve asked the wrong question, forgot about the XY problem lol. Anyways, what could be the reasons that the body that is entered doesn’t actually print? The rigidbody should collide with staticbodies. And then it should print the body that is entered (for debugging purposes)

1 Like

RigidBodies must have contact monitoring enabled with at least 1 max contact report for body_entered to emit.

2 Likes

Your syntax is incorrect. _on_body_entered is your method name, not the signal. The correct should be body_entered:

connect("body_entered", self, _on_body_entered)

This inside your asteroid script.

Thanks gertkeno! You’re a huge lifesaver. I’m a beginner thus didn’t know that. I maybe have taken the wrong approach of learning godot by watching one 15-minute video of the basics and then just figuring it out through trial and error. Anyways, you’ve gotten me a bit closer to a finished game, so I hopefully can submit to the Game Off Jame in time :wink: Take my upvote for your comment!