CollisionShape2D shape not being set correctly in GDScript code

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Beamer159
:warning: Old Version Published before Godot 3 was released.

I have an Area2D node with a child CollisionShape2D node. The CollisionShape2D does not have a shape. I would like to give it one in the code during the _ready() function. I used the following code:

var shape = RectangleShape2D.new()
shape.set_extents(Vector2(50,50))
get_node("CollisionShape2D").set_shape(shape)

Unfortunately, this did not work. It did not call the _inputEvent(…) function when it should have. Out of curiosity, I gave the CollisionShape2D a shape and tried the following code:

var shape = get_node("CollisionShape2D").get_shape()
shape.set_extents(Vector2(50,50))
get_node("CollisionShape2D").set_shape(shape)

This code worked, so I can use this if necessary. However, I would like to know what is wrong with the first code snippet?

:bust_in_silhouette: Reply From: sol

Try this:

var shape = RectangleShape2D.new()
get_node("CollisionShape2D").set_shape(shape)
shape.set_extents(Vector2(50,50))

The same sequence is required in a lot of cases as it seems that objects have to be added to the tree before any of their physical properties can be set in order for them to work correctly.