onready working fine with _ready() but not with _process

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Prateek Amana Gurjar
extends Node
onready var gem = preload("res://Scenes/gem.tscn")
onready var gem_container = get_node("gem_container")

var screensize
var score = 0
var level = 1

func _ready():
	screensize = get_viewport().size
func _process(delta):
		if gem_container.get_child_count() == 0:
		print("Gem container hasnt been loaded")
func spawn_gems(num):
	for i in range(num):
		var g = gem.instance()
		gem_container = add_child(g)
		g.set_position(Vector2(rand_range(40, screensize.x-40),
							   rand_range(40, screensize.y-40)))

it keeps spamming “gem_container hasnt been loaded” in the debugger.
How do I make it so that it loads my gem container in _process() ?

:bust_in_silhouette: Reply From: MysteryGM

The shortcut onready is the same as placing the variable in _ready(). That makes it a local value.

var gem = null
onready gem = preload("res://Scenes/gem.tscn")

This should work.

This is entirely incorrect. onready is equivalent to

var gem

func _ready():
    gem = preload("res://Scenes/gem.tscn")

The variable is declared in the outer scope and is not local to _ready(). onready is just a shorthand to avoid having to write the two separate lines.

kidscancode | 2018-10-12 16:51

:bust_in_silhouette: Reply From: kidscancode

If the gem_container variable is null, that means that it did not get the correct node path. Your problem is in get_node("gem_container").

Is gem_container a child of the current Node? If not, you need the correct path to reach it. You can find the node’s path by right-clicking on the node in the tree and selecting “Copy Path” or dragging the node from the tree into the text editor.