+1 vote

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 = RandomNumberGenerator.new()
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 !

Godot version 3.3
in Engine by (46 points)

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

Please log in or register to answer this question.

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 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 webmaster@godotengine.org with your username.