This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

My project overview:

scene tree and subscene

I made a simple scene, and the subscene named Coin, while I create a script in the root node: Game, I cannot use get_tree() in the _init() function:

func _init():
    var tree = get_tree()
    print(tree) # got nil here!

So I change to use signal in Game node: tree_entered() , now the get_tree() is not nil, however I still cannot get the nodes in specified group (coin group here ):

func _on_Game_tree_entered():
    var coins = get_tree().get_nodes_in_group('coin')
    print('coin size: ', len(coins)) # coin size: 0

So how to correctly use get_tree().get_nodes_in_group('coin')? I found that if I add this code yield(get_tree(), 'idle_frame') before retrieving the nodes in groud, but that's not what I WANT, so how to solve this problem? Help me, and thanks very much!

in Engine by (124 points)

1 Answer

+1 vote
Best answer



in _ready() method. When this method is called all children of given node are already added to the tree.

_enter_tree() is called before Node's children are added.

_init() is called when object is created, so before it enters tree. get_tree() returns a SceneTree that owns this Node so it will return nil in _init() because noone owns this Node yet.
I don't know if it's possible to create multiple SceneTrees. If it is or if it's planned then it makes sense for get_tree() to work like that.

by (2,308 points)
selected by

Thanks so much!
I confused with the _init() function and the _ready() method.
It works now, thanks!

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 Frequently asked questions and 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 [email protected] with your username.