Passing arguments to root node when instancing a scene?

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

I have a scene who’s root node takes some arguments at instantiation time (that is, in _init(arg1, arg2). Unfortunately, I don’t see a way to pass arguments to said node when instance()'ing the scene containing it.

If I just blindly call instance() anyway, it seems like the node is simply ignored. Is there a way to do this?

I had the same problem and solved it with a very ugly hack

coffeeDragon | 2018-06-26 08:16

:bust_in_silhouette: Reply From: Zylann

There is currently no built-in way to pass arguments to a scene like that. You have to call a function of yours probably, like this:

var scene = preload("your_scene.tscn").instance()
scene.initialize(params) # init root node
add_child(scene)

There might be only one case where _init will be called, is when you do this:

var node = preload("your_script.gd").new(params)
add_child(node)

But for scenes, you have to go the other way.

Thanks, I did a preload("script.gd").new(arg1, arg2), where script.gd instantiates its child nodes in _ready(), and that indeed worked.

Is there any particular reason to use scenes instead of a script like this then? I suppose if you have custom collision shapes or some node which really wants to be set up with the editor, that might be a good reason to use a scene. Is that the only reason?

gandalf3 | 2018-06-27 01:50