Is there a way to return a constant name to create an instance in another function?

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

I am trying to create a function which will determine which item to create an instance of. To do this I am trying to create a function which returns the preload constant to be instanced. I have tried a few things but none of them worked like

const EXAMPLE = preload("res://example.tscn")

func create_instance():
    var i = _returnfunction

func _returnfunction():
    return EXAMPLE.instance()

the above instances it but i is null so this function doesnt work (there is more code which changes values in the instance)

I also tried returning a string of the correct constant name but couldnt instant that either and tried just returning the constant and then creating another variable with an instancing of the var with the return value but this didnt work either. Does anyone know how to use a return function to pass a constant name so it can be instanced elsewhere?

:bust_in_silhouette: Reply From: Pomelo

You lost me a bit with what you want, but to instance a scene you only need to know the path. Once you have the path, you just load and instance it. So if you want an object to tell another object to instance something, you send the path (with a signal, a function or whatever you see fit). I would just use a signal, but with a function it would look like this:

## The object that knows the path (lets call it Knower)
var path = "res://example.tscn"
func get_path():
    return path

## The object that instance the scene
var knower = Knower # Up to you to get the node/object/script
func create_instance():
    var loaded_scene = load(Knower.get_path())
    var scene = loaded_scene.instance()

If it is all happening in the same object, you dont even need to complicate yourself that much (I am assuming you need to select from a few different paths):

var list_of_paths = ["...", "...", etc...]

func get_correct_path(i):
    return list_of_paths[i] # for example

func instance_from_path(path):
    var loaded_scene = load(path)
    var scene = loaded_scene.instance()

you then call it instance_from_path(get_correct_path(3))

You also kinda not need the last function you can just go var scene = load(get_correct_path(3)).instance()

Edit: The functions that I wrote are redundant of course, they are just for the example.

Thank you that really helped

YuleTide | 2022-06-13 21:26