How to make signals send once a certain condition is met

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

Right now, I am making an rpg game that requires you to open chests with keys.
extends StaticBody2D

signal chest_opened

var keytaken = false
var in_chest_zone = false

func _on_Area2D_body_entered(body: PhysicsBody2D): #area2d - > key
if keytaken == false:
keytaken = true

func _process(delta):
if keytaken == true:
if in_chest_zone == true:

func _on_chest_zone_body_entered(body: PhysicsBody2D): #chest zone → key
in_chest_zone = true
extends StaticBody2D

onready var only_once : bool = true
onready var animationplayer = $AnimationPlayer

func _ready():“Idle”)

func _on_Key_chest_opened():
if only_once == true:“Open”)
only_once = false
The problem with this is if the player enters the chest zone before the key is collected, as soon as the key is collected, the chest opens.
I want the chest to only open once the player has the key and has entered the chest zone; whether or not they have previously done this.
If anyone could come up with a fix, I would greatly appreciate it.
Using GDScript.

:bust_in_silhouette: Reply From: matthewjw

I’m a little confused with what you wrote, but I hope this helps.
You don’t need to be checking for key and chest status all the time with process(delta).

Think about the problem like this:

#When player enters chest zone 
#Check if the chest has been opened
#If chest is closed, check if the player has key
#if the player has a key, call the open chest function
#use a boolean to remember that your chest is open