0 votes

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?

in Engine by (12 points)

1 Answer

0 votes

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.

by (28,972 points)
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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.