accessing their parents from instanced scenes

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

Hello,
I am not sure if i did this wrong the whole way through, but let me explain:
I have a WindowDialog packed in an individual scene, which is instanced to the “UI”, which is then instanced to the Main scene. I now need to somehow execute a function in the script from “World”, which is instanced in “Main”, from the script in "WindowDialog ", because if a button in the WindowDialog is pressed, a new world should generate. I know this would be easy if i didn’t use instancing and would put all the code into the main-script, but i find it this way to be very organizing, so i want it to stay that way if possible.

Thanks for any help

:bust_in_silhouette: Reply From: DavidPeterWorks

So you want to call a function in main from a button that is instanced in run-time right?

At the end of world generation you can:
1,
Connect a signal from main.
find_node(“generatorButton”) .connect(“button_pressed”, self, “main_generator_function_in_main”))

2,
You can create a Singleton object and set your main object to it.
It is an empty node with script that has some vars for each important objects, like main, world etc.
You set these variables in the singleton in the ready method.
MySingleton.mainObject = self
You can reach this singleton container and access the main and it’s methods.
You can use this object in the on_press event. MySingleton.mainObject.generateNewStuff()

Thank you,
I didnt know about the findnode(), that makes it easy

Alidro | 2019-05-13 12:56

:bust_in_silhouette: Reply From: Dlean Jeans

I would create a signal called new_world_requested or whatever in Main and optionally in UI and the WindowDialog depending how much decoupled you want them to be.

Now when the button is clicked, it emits the new_world_requested signal from the UI which is then forwarded up to Main which is connected to the function generate_new_world I supposed, in World.

Pseudo code:

# CreateWorldDialog.gd
func _on_create_world_clicked():
  emit_signal('new_world_requested`)
  # or less decoupled
  get_parent().emit_signal('new_world_requested`) # from UI
  # even less decoupled
  get_parent().get_parent().emit_signal('new_world_requested`) # directly from Main


# how to forward the signal if you use the one of the first two ways:
# put this in CreateWorldDialog.gd and UI.gd
func _ready():
  connect(`new_world_requested`, get_parent(), 'emit_signal', [`new_world_requested`])

i thought about that, but without findnode() i would have to use get_parent() very often, like 5 times because its so interlaced.

Alidro | 2019-05-13 12:58