0 votes

I'm trying to connect by code a custom signal from the Main node to a child.

I tried this:


but it doesn't seem to work.

It works when I connect the signal manually from the engine, so what am I writing wrong?

in Engine by (374 points)

1 Answer

+1 vote
Best answer

get_tree() returns the SceneTree, not whatever your Main node is. You need to get the node using get_node() and whatever the path to the node is.

You can use get_parent() to get the node's parent.

by (19,225 points)
selected by

I tried $ which is the same as get_node() or that's what I've read but it didn't work gave me an error about an invalid instance but get_parent() works thanks.

One more question what if it was the grandchild I would have to do: get_parent(get_parent()) is there a way to get the root node from wherever?

$ and get_node() are interchangeable, but if you want to go up a level, it would be get_node("..") or $"..". To go up multiple levels, you'd use get_node("../..") etc.

get_tree().root will get you the root viewport, so you can get your main node from that:

get_tree().root.get_node("Main") for example.

All this said, it's typically a bad idea to be going up the tree. It means you're not going to be able to move nodes around because they expect a fixed parent structure. It's much more flexible to call down the tree, and use signals if you need to go up.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.