|
|
|
|
Reply From: |
pheryx |
In my projects I use a generic function to initialize each instanced scene and pass references to the global node, root node, and current node. This gives instanced scenes a reference to all three, which can be traversed upward through parent.parent.function()
or downward with root.node_name.node_name.function()
.
You will always call init_root()
before adding the child to the stage. Or, if the scene is instanced inside another scene, you’ll call init_root()
from the parent scene’s _ready()
function. This way, init_root()
is always called before firing any _ready()
function. By the time the child’s _ready()
fires, it will already have access to your other nodes.
In Godot, every object is passed as reference, so this does not impact your performance. It gives you an easy way to reference your other scenes, nodes, and properties.
The child script:
var global
var root
var parent
func init_root(global_node, root_node, parent_node):
global = global_node
root = root_node
parent = parent_node
func _ready():
pass
Then, from the parent script:
var internalScene = null
var externalScene = null
func _ready():
internalScene = self.get_node('instanced_scene')
internalScene.init_root(global, root, self)
# or
externalScene = load('res://scenes/loaded_scene.scn').instance()
externalScene.init_root(global, root, self)
self.add_child(externalScene)
Thanks, I am glad I asked about this, cause I am learning a lot.
And adapting your case to my example, what would be the difference between the global and the root nodes?
cardoso | 2016-06-11 10:19
Global is a script you create that can be autoloaded with any running scene. The root node would be the currently running scene. When you change scenes, the new scene will become your root node, but the global script would be loaded the same.
Using a global script is optional. It functions exactly as a node. It allows you to carry common variables, functions, and settings among different root scenes. You can read more in the documentation for Singletons (AutoLoad).
pheryx | 2016-06-11 11:42
Ah ok, you mean global in that sense. I don’t know why but I thought You meant global would be the top most scene holding the other instanced scenes.
cardoso | 2016-06-11 12:38