I use this code: Scene1

    func _unhandled_input(event):
    	if Input.is_action_pressed("lpm"):
    		p = preload("res://KinematicBody2D.tscn").instance()
    		add_child(p)
    		p.position=get_global_mouse_position()

and i use button for clear but

    func _on_remove_pressed():
    	p.clear()

And I would like to delete all children, but only the last one is removed

I usually use logic like this to add and remove children:

if self.get_child_count() > 0:
	var children = self.get_children()
	for c in children:
		self.remove_child(c)
		c.queue_free()
	add_child(your_node_instance)
else:
	add_child(your_node_instance)

The reason it doesn't work is because you overwrite "p" every time you spawn a new object, so "p" only refers to the last object created. What you can do is keep an array with all your added objects (you add the "p" object every time you spawn one), then loop through the array when you remove them. And don't forget to reset the array after you are done.

I have a problem because it removes all children, including my buttons (GUI), and I would like to remove only all kinematicbody. I have an idea but I don't know if it will work. There is a "get_child_count" function that shows the number of children When I open Scene and I have 3 children(2 buttons and timer). And is it possible to delete all children above number 3? I am asking for your understanding, I am still learning programming

Something like this I guess

if get_child_count() > 0:
    var children = get_children()
    for c in children:
        if c > 3 and c == KinematicBody2D:
            remove_child(c)
            c.queue_free()
note: untested.

I think it should actually be like this:

for obj in get_children():
	if obj is KinematicBody2D:
		remove_child(obj)
		obj.queue_free()

Or join the group,like this ,you can decide what needs to be deleted

obj = preload("res://KinematicBody2D.tscn").instance()
add_child(obj )
obj.add_to_group("needDelete")

for obj in get_children():
    if obj.is_in_group("needDelete"):
        remove_child(obj)
        obj.remove_from_ group("needDelete")
        obj.queue_free()

In addition

And is it possible to delete all children above number 3? it is a disaster, 1. In terms of code maintenance. - no one else can understand; - The system singleton node will be added to the beginning, you have to change the number - If you need to dynamically change the order of nodes in your code

3 years later