How do I have the root node to connect a signal to itself via the code (C#) way

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

Here are all my notes

*Player ←it’s an Area2D node
-AnimatedSprite
-CollisionShape2D

I just want to have the body_entered signal from Player node to connect Player node itself.

Here is what I tried.

    var Player1 = (Area2D)GetTree().GetRoot();
	Player1.Connect("body_entered",this,nameof(_OnPlayerBodyEntered));

Error meesage is: Cannot convert type ‘Godot.Viewport’ to Godot.Area2D’

But if I change the code var Player1 = (Area2D)GetTree().GetRoot();to var Player1 = (Viewport)GetTree().GetRoot();Then I got warning message about the "object of type Viewport try to connect nonexistent signal to method about Area2D, and it’s not connected correctly.

Could you let me know what’s happening, and let me know how to do this signal connect via the code way?

Thanks a lot!

:bust_in_silhouette: Reply From: RenenerG

Hello Godotfan,

I assume that you want to get the player’s node here, right?

var Player1 = (Area2D)GetTree().GetRoot();

What you getting here is not the player node. It is the root of the scene, which is basically the viewport. Thats why you getting this error:

Error meesage is: Cannot convert type ‘Godot.Viewport’ to Godot.Area2D’


What does your scene looks lilke? Something similar to this?

Player (Area2D)
---- AnimatedSprite
---- CollisionShape2D

Then, you need to get the Area2D node, which means that you have to extend your approach to do something like this:

var playerNode = (Area2D)GetTree().GetRoot().GetNode("Player");

But if I change the code var Player1 = (Area2D)GetTree().GetRoot();to var Player1 = (Viewport)GetTree().GetRoot();Then I got warning message about the "object of type Viewport try to connect nonexistent signal to method about Area2D, and it’s not connected correctly.

It’s because a Viewport does not provide a signal called “body_entered”. Only Area2D and RigidBody2Dhave such signals.


Could you let me know what’s happening, and let me know how to do this signal connect via the code way?

I really suggest you to read the documentations Step by step. There is everything explained, what you need. From basic scripting to signals to physics, etc. Good Luck! :slight_smile:

Thanks a lot!

Godotfan | 2019-02-21 15:51