0 votes

Scene hierarchy:

-Spatial
---Spatial (with script)

√ Camera working:

extends Spatial

func _ready():
    var camerra = Camera.new()
    add_child(camerra)

× Camera not working:

extends Spatial

func _ready():
    var camerra = Camera.new()
    get_parent().add_child(camerra)

If I add the Camera node in the node itself, it moves, rotates, scales with the inner Spatial, that does not work for my use case. I need the camera to have the same parent as the child node. However, when I run the second code, I get a gray screen while the first code does what it should.

asked Jun 19 in Engine by OnSr (16 points)

Strange :/ try print(camerra.get_path()) or print(get_parent().get_path()) before calling add_child(). If nothing is printed you might have to use yield(get_tree(),"idle_frame") before calling anything else.

Thank you very much. Strangely yield(gettree(),"idleframe") solves the problem. I though ready was already called after ***idleframe*** was emitted.

I think we might need to open an issue about this.

1 Answer

0 votes

This is how I solved it. I hope it does not cost much performance.

extends Spatial

var camerra
var isCameraOn = false

func _ready():
    camerra = Camera.new()
    add_child(camerra)

func _physics_process(delta):
    if !isCameraOn:
        remove_child(camerra)
        get_parent().add_child(camerra)
        isCameraOn = true

yield() commented by @Magso also works. Maybe it works even better than this. I just wanted to let know this is what I am using.

Update:
Turns out there is an error which I did not notice before. There is also an advice in the Debugger.

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

So, the working code I am currently using is:

extends Spatial

var camerra
var isCameraOn = false

func _ready():
    camerra = Camera.new()
    get_parent().call_deferred("add_child", (camerra))
answered Jun 21 by OnSr (16 points)
edited Jun 22 by OnSr
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.