+2 votes

Is there a way to access nodes of a scene before instantiating it?
I need that to know which and where to spawn generated level sections in my game.

in Engine by (28,738 points)

2 Answers

+1 vote

Maybe, someone will give you a better answer, but you can use function get_state() in PackedScene. This object holds information about your scene, so you can for example loop through each node (get_node_count()) and get the information you want (get_node_property_name/value). The problem is that SceneState is read-only object.

I think you could also make an instance of the scene, do your stuff with it (remember, you are able to access the nodes you want, beacause you have a reference to root node) and put the scene to Scene Tree, when you are ready.

by (822 points)
edited by

Read-only is fine, it's just a matter of knowing beforehand how big is the scene and where are its "connection" points :)

I look at SceneState, but none of the function take a NodePath... instead, they take integer indexes. How can I query PackedScene for nodes by path?

+2 votes

You can also access nodes of a scene right after it is instanced, but before you call add_child. Beware though, onready variables would still be uninitialized, and neither _ready nor _enter_tree would have been called. This means that the nodes are still not really ready to work with, and might give weird errors on things that normally work. E.g. functions like set_pos might work and change the position, while a utility function that calls expects _ready to set some nodes for it might fail. YMMV.

Another idea would be to thinker with the node right after add_child, which would still be before a new frame is drawn, but after _ready has finished processing. This might be the best idea if you have a lot of utility functions in the instanced scene's scripts, since they would be fully initialized at that point.

A third option (Before instancing, but it's readonly) is discussed by @GlaDOSik in his answer.

by (1,590 points)
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.
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 webmaster@godotengine.org with your username.