Help needed in rng

Godot Version

extends Node2D

var clicks = 0

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

var rng = RandomNumberGenerator.new()
var rndX = rng.randi_range(0, screenSize.x)
var rndY = rng.randi_range(0, screenSize.y)

func _on_texture_button_pressed():
clicks += 1
$TextureButton.position = Vector2(rndX, rndY)
$RichTextLabel.text = str(clicks)
print(clicks)

Question

i dont know how to fix this error: Cannot call method ‘get_visible_rect’ on a null value

Try adding an @onready annotation:

@onready var screenSize = get_viewport().get_visible_rect().size

I do think tayacan is right, but keep in mind the initialization order:

It might need a general structure improvement such as:

extends Node2D

var clicks = 0

var rng := RandomNumberGenerator.new()
var rndX: int = 0
var rndY: int = 0

@onready var screenSize: Vector2 = get_viewport().get_visible_rect().size

# It is advised to cache the node that might be accessed multiple times like the following ones.
@onready var texture_button = $TextureButton
@onready var text_label = $RichTextLabel

func _ready():
    rndX = rng.randi_range(0, screenSize.x)
    rndY = rng.randi_range(0, screenSize.y)


func _on_texture_button_pressed():
    clicks += 1
    texture_button.position = Vector2(rndX, rndY)
    text_label.text = str(clicks)
    print(clicks)

Alternatively if you want the button to move after each time being pressed:

extends Node2D

var clicks = 0

var rng := RandomNumberGenerator.new()
var rndX: int = 0
var rndY: int = 0

@onready var screenSize: Vector2 = get_viewport().get_visible_rect().size

# It is advised to cache the node that might be accessed multiple times like the following ones.
@onready var texture_button = $TextureButton
@onready var text_label = $RichTextLabel

func _randomize_position()
    rndX = rng.randi_range(0, screenSize.x)
    rndY = rng.randi_range(0, screenSize.y)


func _on_texture_button_pressed():
    clicks += 1
    _randomize_position()
    texture_button.position = Vector2(rndX, rndY)
    text_label.text = str(clicks)
    print(clicks)

Hope it helped

1 Like