0 votes

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()

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

asked Jul 2, 2019 in Engine by soulldev (56 points)

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

1 Answer

0 votes

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())).

answered Jul 3, 2019 by Zylann (26,967 points)
edited Jul 3, 2019 by Zylann
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.