Help with Clickable Area2D and a selection indicator

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By JCNegar

So, I am trying to implement a selection indicator (an orange square that appears around the Selected sprite) and I came up with the idea of instancing that selection indicator at the position of my selected node (I know I can use shaders but as of now, that’s above my understanding I don’t want to rush.)
So here is my code:

extends Area2D
var selected = false
onready var selection = preload("res://SelectionIndicator.tscn")
func _input_event(viewport, event, shape_idx):
    if event is InputEventMouseButton \
    and event.button_index == BUTTON_LEFT \
	    and event.is_pressed():
	    self.on_click()
	
func on_click():
    selected = not selected
    if selected:
	    var selection_instance = selection.instance()
	    selection_instance.position = position
	    get_parent().add_child(selection_instance)
    else:
	    # I want to hide the selection indicator when the Area2D is unselected

So, I got the selection thing working, However, I am not able to figure out how to unselect and hide the Selection indicator, I used queue.free() tried also remove_child(), Nothing seems to be working, I am pretty sure I am missing something simple, Any help is appreciated!

P.S: The Selection Indicator is a Sprite.

Would you share how you tried to queue_free or to remove the child?

Also, if i were you, i would have the selection_instance always present. just hide it when unselected it. But perhaps you have other reasons to do this

p7f | 2020-09-13 00:06

another possible option is to use buttons which already have a feature called focus to show selection, you can style this focus in theme or with custom styles to be an orange outline or whatever

if they are selectable they need to be buttons anyway to get pressed event to handle selection? idk

for example if you make a new scene and add a vbox and 3 buttons the one you click will be highlighted with the focus

but ya queue_free should remove it i would think

rakkarage | 2020-09-13 02:39

Variables made in an if statement can only be used with in that if statement. Also the function is called once every click so it would lose the reference every time, it needs to be made a scipt variable and the instance needs to be assigned in ready()

Magso | 2020-09-13 08:58