Click to Delete Instantiates

Godot Version

Godot 4.2 - 2D

Question

Currently, I have my Godot to where if I right-mouse-click, I create a “Rat” instantiate at the mouse location. “Rat” has an Sprite2d Image, Area2d and CollisionShape2d. If I randomly right click on the screen, a rat instance will appear wherever I clicked. How do I get it to where I can left click on the Rat instance and have it deleted?

Area2D has input_event signal that can detect clicks (CollisionObject2D — Godot Engine (stable) documentation in English). You can use this to detect if the rat is left clicked.

Does this work for an instantiated area? It works with the original sprite but not the instantiated one.

It should work regardless of whether it was instantiated or not. If you’re connecting the signal to another script outside of the rat scene through the editor, you also have to do it through code.

I’m not sure why it is still not working.

func _on_rat_area_2d_input_event(viewport, event, shape_idx):
print(“Hello”)

This seems to only work with the original.

And this is how I instantiate it.

var c = ratSpawn.instantiate();
c.global_position = event.position;
get_parent().add_child(c)