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!

asked Nov 6, 2018 in Engine by SpkingR (126 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.

answered Nov 6, 2018 by hilfazer (2,112 points)
selected Nov 7, 2018 by SpkingR

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 How to use this Q&A? before posting your first questions.