why i get "null" when i use get_owner function from script attached to added node?

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

i want use get_owner function for get root node(top node).

but i can not get top node from script of added node.
i make parent node.
and i created a node named “child” under it.
“added node” added by script from the “parent node”.

node structure of node is like this.
**parent(attached parent.gd)
***added_child(attached added_child.gd)
enter image description here

parent.gd(parent.gd called added_child scene,and output it.)

extends Spatial

var added_child = load("res://test/added_child.tscn");

func _ready():
	var instance = added_child.instance();

added_child.gd(this script output “[Object:null]”)

extends Spatial

func _ready():

thank you,please help about this.

:bust_in_silhouette: Reply From: jgodfrey

Calling add_child() does not set the owner property of the added node. Instead, it sets the node’s parent. The parent of a node can be retrieved via get_parent().

Bottom line - change your get_owner() call to get_parent().

Thank you very often. understood about it.

i decide get the root node via parent node.

but there are a few question.
why added node not have owner property?
spatial node inherits node class with owner property.

bgegg | 2022-04-17 02:10

why added node not have owner property?

I’m not sure I understand your question. Anything that inherits from Node will have an owner property (as you correctly stated). So, the node you added does have an owner property, but it is not automatically set by calling add_child().

That’s because an owner does not have to be a direct parent. So, you should expect owner (and thus, get_owner()) to return null unless you’ve explicitly assigned it to something.

jgodfrey | 2022-04-17 02:34

Thank you very much.
I found out that I need to set the owner property.
I thought the added node would have an owner by default.

bgegg | 2022-04-17 05:12