get_parent().get_child_count() 'null instance' error when child is instanced scene

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

The following code was working in a node, representing a card in a deck-building game.

var deck_size = get_parent().get_child_count()

I then changed the node into a scene and instanced it as a child of a container, and now receive the following error:

Attempt to call function ‘get_child_count’ in base ‘null instance’ on a null instance.

Apologies if there is a really obvious reason why this doesn’t work in the new context - I am struggling to get my head around scope generally.

Thanks in advance!

:bust_in_silhouette: Reply From: njamster

Attempt to call function get_child_count in base ‘null instance’ on a null instance.

This means you’re attempting to call a method on a node, but that node is actually not there, usually due to a wrong path. As you’re using get_parent, I can only imagine that you’re calling this method before the scene is added to the tree, e.g.:

root-node

var child_node = load("<PathToScene>").instance()
child_node.init()
add_child(child_node)

child-node

func init():
    get_parent().get_child_count()

Great, thanks, the issue was to do with calling it too early.

jamesgiddings | 2020-04-01 14:12