0 votes

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?

in Engine by (51 points)

1 Answer

0 votes
Best answer

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.

by (418 points)
selected by

Thank you that really helped

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.