Godot Version
4.4
Question
so in most videos and posts i saw about Compositions people tent to make the Component as a child and use @export to connect it to the parent or other stuff … is this the way to go ? im always forgetting drag everything into the export is there no good way for the parent to grab a component by type or so? i mean what happens if i want to dynamicly add a component how would i connect it because i obviously can not drag and drop some stuff at run time. So wahts your way on doing stuff dynamicly and are drag and drop all your compontes always by hand?
thanks for helping a noob to wrap his head around thees concepts 
the general rule is call down, signal up. it is a bit up to the programmer to figure out the best way of doing things because it greatly depends on the specific game you are making. there is no “fit-all” way of doing things, you need to think of the needs of your game, design everything, and then start coding once you know what needs to happen.
of course you can also just start, but that will lead to a lot of debugging and re-writing of the code, which is fine, it depends. for smaller projects this works fine.
there are no components in godot, there are nodes.
you can do it in code by using get_children()
and iterating over them until you find it.
here we look for an Area2D
. the way to test for a type in godot is to cast to that type and check for null, that is how it works internally.
var area : Area2D
func _ready() -> void:
for i in get_children():
area = i as Area2D
if area:
break
this is not optimal, it is always better to build a scene by hand and add the nodes you need and then obtain them using @onready
@onready var area_3d : Area3D = $Area3D
you can also just connect a signal
from the node to the parent or to other node from the node tab in the inspector.
for that we use references.
the moment a node is added to say the character, we connect it with signals or assign it to a reference through code. again, it depends on what you are trying to do and it’s not always a good idea to make it dynamic if you don’t need to.
this could also happen as a result of a collision, and in that case we would get a reference to the node called something like body
.
1 Like
I’ve seen this too especially from people coming from Unity and Unreal It’s not the Godot way to do things. Like @jesusemora said, use an @onready variable.
- Add the Node to your scene tree.
- Open the script in the Script Editor.
- Drag the Node from the scene tree over the code.
- Press the Ctrl key and then let go of the mouse button.
You will now have a line that looks something like:
@onready var idle_timer: Timer = $IdleTimer