T
Tragedy
posted to: Coding the spawners

Spawn() not work if called directly from Spawner.gd script

Hi, if i call spawn() function directly from Spawner.gd script (in _ready() function), then nothing spawn. When called from Testroom, it works. Just don't know why...

  • Nathan Lovato replied
    I would need to open your project in Godot to tell you why that is. could you zip the project folder from your file browser and upload it to a platform like google drive? I'll open it in Godot and tell you why you are seeing this strange behavior.
  • T
    Tragedy replied

    Thanks for reply. Here is whole project ZIPed: https://www.uschovna.cz/en/zasilka/CRUHTCRAWC3M7T5W-GPY/SS2I2L4UHX "Test room" is set as main scene and inside it is spawner with script, where "spawn" is called from "_ready()" function. Nothing happens. I am really currious, becouse when called outside this script (from "testroom script"), it works.

  • Nathan Lovato replied

    After testing, here's what the problem is: the call to the ready function first happens on child nodes before their parents. So when you call the spawn() function from the spawner in its ready function, its parent isn't ready to receive new children yet.

    It's just a rule in the way nodes work in Godot: they can't add children until they're ready.

    But we have this line in the spawner script:

    func spawn():
    #...
        get_parent().add_child(node)

    We are trying to add the new instance as a child of the parent node.

    You can make the call work by writing this instead:

    get_parent().call_deferred("add_child", node)

    The function call_deferred() will delay the call to add_child() until the current processes completed (it waits until something called "idle time", which is typically the end of a frame), which, in this case, ensures that the parent is ready.

    How you would figure this out on your own

    Now let's talk about how you can solve an issue like this on your own. You would use the debugger.

    In the next update, we are adding a new chapter dedicated to debugging, and this tool called the debugger. What I'll show you next is something we haven't covered yet in the course but that you will learn with our upcoming release (it's almost there, our editor's reviewing the new chapter).

    At the bottom of the editor, if you open the debugger and then navigate to the errors tab, you will see that your function call triggers an error. And this error doesn't cause the game to pause like some others.

    You can see on the error message that it recommends using the call_deferred() function.

    I hope this helps clarify what happened.

    1 love
  • T
    Tragedy replied

    Thank you very much for detailed reply. Now it makes sense.