Instantiate a scene through a string name contained within a variable?

Godot Version

Godot 4

Question

How do I instantiate a scene from a string contained within a variable? I have a variable which contains the string “res://scripts/enemies/droidtest/droidtest.tscn”. I then try to instantiate this scene through the variables by calling the autoload I made for this script and then the variable name which was current enemy and then instantiate.

var enemy_instance = BattleVariables.current_enemy.instantiate()

However, running the code results in the error on that line:

Invalid call. Nonexistent function 'instantiate' in base 'Nil'.

Use load or preload with the variable

preload(my_res).instantiate()

Since it is a global script function. You could put the that preload in a static function on the class.

Const my_res_var = "res://some_scene.tscn"
Class_name MyScene
Static func create()-> MyScene:
  Return preload(my_res_var).instantiate()

I have already tried preloading, and I’m mainly trying to instance a scene by calling a variable (in which the scene is contained within the variable as a string). I just want to know if that is even possible to instance a scene from within a variable, because it is not working with preload on my code.

A variable with a string of a res path needs to be loaded first. As instantiate() is a packedscene function.

So no, unless you load/preload first a string is not a packedscene.

This static method provided above is the best way, because if you preload in a class used many times it will consume memory. You could I guess preload it without instantiating, just make it static.

1 Like
Const my_res_var = "res://some_scene.tscn"
Class_name MyScene
Static my_packed_scene = preload(my_res_var)

Use

MyScene.my_packed_scene.instatiate()