Instancing same scene godot

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

I have a problem when I want to instance a node from the same scene, I made a PackedScene var that point to the same scene type, I want to recursive the instantiation so each same could instance another scene of itself:

var s= s.instance()
add_child(s) 

but I get the error:
Invalid call. Nonexistent function ‘instance’ in base ‘Nil’.

You probably wanna remove the var part if you wanna it to be recursive.

Dlean Jeans | 2019-07-02 12:48

:bust_in_silhouette: Reply From: Zylann

You get this error because you created a variable s while s actually exists already, as a class member I assume:

var s = 42

func _ready():
    var s = s
    print(s) # Prints "Null"

After testing this myself, it seems Godot doesn’t issue any error or warning in this case, which is unfortunate, because what ends up in s is the uninitialized value of the local variable itself, NOT the previously defined s. So you get null.

To fix this, either use a different name, or don’t use a var (add_child(s.instance())).