• Godot Help
  • Why am I unable to get window size information in my script?

Hello there,

I am a bit new so sorry if this is a dumb question.

I have been trying to follow along with some tutorials and was using some code from https://github.com/Godot-Tutorials/Movement-No-Input-Solution/blob/master/Hero.gd

At the top of this script, the author begins the script by defining the window size.

extends Sprite

var gameWidth: int = OS.get_window_size().x
var gameHeight: int = OS.get_window_size().y

When I try doing this however in 4.0, I get an error saying cannot call function get_size() on a null value.

Here is my code

extends Sprite2D


var gameWidth: int = get_window().get_size().x
var gameHeight: int = get_window().get_size().y
var spriteWidth: int = get_texture().get_width()
var spriteHeight: int = get_texture().get_height()

@export var velocity: float = 100.0
@export var acceleration: float = 300.0
@export var max_speed: float = 1500.0


func _enter_tree():
	positionLeftCenter()

How come I am unable to use the get_window() function at this point of my script yet the get_texture() works just fine. In the debugger it also says at function: @implicit_new.

The following however works just fine

extends Sprite2D

var gameWidth: int 
var gameHeight: int 


@export var velocity: float = 100.0
@export var acceleration: float = 300.0
@export var max_speed: float = 1500.0


func _enter_tree():
	gameWidth = get_window().get_size().x
	gameHeight = get_window().get_size().y
	positionMiddle()

Any help welcome!

  • xyz replied to this.

    Hotcrossbun You're trying to initialize properties before the node is added to the scene tree. The node can't figure out in which window it lives if it doesn't belong to a specific scene (which in turn belongs to a specific window)
    Either try:

    @onready var gameWidth: int = get_window().get_size().x 

    or initialize width/height properties in the _ready() callback:

    var gameWidth: int
    func _ready():
        gameWidth = get_window().get_size().x

      xyz Thanks I assumed that would be the case based on how it worked.

      I guess what confuses me is why did this work in the example code I provided in the github project for Godot 3? Is this because they were getting the value from the OS class rather than the scene? I guess I am also still slightly vague around the concept of what exactly the window is vs the screen vs the scene etc.

      Appreciate the help!

      • xyz replied to this.

        Hotcrossbun Note that in Godot 3 example the window size is obtained via OS singleton object which is always initialized and has nothing to do with any specific node. In v4 they removed it from there and put it into the Node class. I guess it's because v4 supports multiple windows while v3 always runs in a single implicit window.