Why get_tree() is nil in init(), and get_nodes_in_group('.') returns 0-size array in tree_entered()

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

My project overview:

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!

:bust_in_silhouette: Reply From: hilfazer



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.

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

SpkingR | 2018-11-07 00:46