Don't understand why get_node is returning null

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By imekon
:warning: Old Version Published before Godot 3 was released.
onready var red = get_node("red")
onready var green = get_node("green")
onready var blue = get_node("blue")

red, green and blue are children of the current node, yet they are null when get_node is called?

Editor tree

main.gd:

onready var _factory = load("res://scenes/blockfactory.tscn")
var factory = _factory.instance()
if factory == null:
    print("no factory!")
    return
var block = factory.createRed(100, 100)
if block == null:
    print("no red")
    return
add_child(block)

_factory is fine, but createdRed fails

blockfactory.gd:

func createRed(x, y):
if red == null:
    print("no red")
         return null
    var block = red.duplicate()
    if block == null:
         print("no block")
         return null
    block.set_pos(Vector2(x, y))
    return block
:bust_in_silhouette: Reply From: volzhs

onready runs after node is added to scene tree.
but you called createRed before it’s added to scene tree.

I see… I forgot to add the instance of factory to the scene tree, once I do that it starts working.

imekon | 2018-01-13 23:41