Problem with "get_visible_rect()"

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

Hi there !
I’m trying to create a spawner for an object in my game. The object is a stopwatch (in french it’s a Chronomètre, so that’s why my object is called a Chrono).

In my spawner, i want to get the screen size to prevent the spawner to spawn beyond game limits. I found a way on the internet, but I get this error:

Attempt to call function 'get_visible_rect' in base 'null instance' on a null instance.

Here is my code:

extends Node2D
var ran =
var chrono_scene = load("res://timer_sus.tscn")

var screen_size = get_viewport().get_visible_rect().size

func _ready() -> void:
func chrono_spawn():
	var spawn_time = ran.rand_range(10, 20)
	var chrono = chrono_scene.instance()
	var x = ran.randf_range(0, screen_size.x)
	var y = ran.randf_range(0, screen_size.y)
	chrono.position.y = y
	chrono.position.x = x

func _on_spawn_timer_timeout() -> void:

Basically, it’s goal is to spawn an object in the visible area of the game randomly.

Thanks a lot !

Try changing:
var screen_size = get_viewport().get_visible_rect().size
onready var screen_size = get_viewport().get_visible_rect().size

timothybrentwood | 2021-09-19 21:33