Add programatically-initialized Node subclass to viewport

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

A function in a class extending Node has the following call:

var viewportWidth = get_viewport ( ).size.x

This works when the script is added to a node in the scene.

However, if the class is initialized as a var programatically (from a node that is part of the scene) it gives me the following error:

Invalid get index 'size' (on base: 'null instance').

How do I add the programatically-created node subclass to the viewport?

:bust_in_silhouette: Reply From: Zylann

var viewportWidth = get_viewport ( ).size.x

Where exactly is this line located?

get_viewport() will only return a Viewport if the node is inside the scene tree. If it isn’t, it will return null, which is probably what happens here.

If the line you quoted is inside the _init function, or outside as a member variable, it won’t work because these locations are executed on creation of the node, before it enters the tree.