[PackedScene].instance() not working in _ready() function

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

Hey fellow godot devs,

I am currently experiencing an issue in godot 3.5.1, where a PackedScene does not get instantiated when I call .instance() in the _ready() function.

E.g.:

export (PackedScene) var platform_scene

func _ready():
  var platform = platform_scene.instance()
  platform.translation = Vector3(0, 0, 0)
  get_parent().add_child(platform)

will not work (no errors and no platform).

However if I add a timeout, it will work:

func _ready():
      yield(get_tree().create_timer(0.1), "timeout")

      var platform = platform_scene.instance()
      platform.translation = Vector3(0, 0, 0)
      get_parent().add_child(platform)

Do you know why this is the case and how to fix this without a timeout?
get_parent() seems to be the culprit but I am currently not sure why.

Cheers

:bust_in_silhouette: Reply From: Florentin

Okay I found the issue, and it is a bit silly that I didn’t see it straight away.

The error message was even displayed in the debugger, I just didn’t realize it because there was no crash and nothing in the output.

So the debugger displayed the following error message:

add_child: Parent node is busy setting up children, add_node() failed. Consider using call_deferred("add_child", child) instead.

So I used:

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

and it worked.

Hope this helps somebody else.

Cheers

Ah - a message containing an explicit and useful corrective action. Nice. Well done devs!

jgodfrey | 2023-01-30 18:04