How to configure Gui Buttons and trigger2D correctly?

This is what I want to achieve:

When the button is pressed AND the object is in the “trigger zone” then destroy the object and reset the button.

If the button is pressed AND object not in the zone, reset the button (unpress it).

The problem is that the button doesn’t get reset when the object is not in the zone, and i can’t think of another way :frowning:

void OnTriggerStay2D (Collider2D other)
{
    if (leftClick) {
             leftClick = false;
             if(other.gameObject.name.Contains("abc"){
             Destroy (other.gameObject); }
	}
 }						
 private void OnGUI ()
 {
    Rect aRect = new Rect (0,0,20,20);
    if (GUI.Button (aRect, "") || Input.GetKeyDown ("left")) {
    						leftClick = true;
    				}
    }

The problem here is that leftClick = false; (to reset button), doesn’t get executed if there is nothing in the trigger zone, so if I press the button before the object enters, it doesn’t get reset.

I want the button to reset to false (unpress) when the object is not in the trigger zone

Sometimes things like this are cumbersome in Unity. I can think of two approaches. If you will only have one collision with the specific type of object at the same time you can do something like this:

void OnTriggerEnter2D (Collider2D other)
{

    if(other.gameObject.name.Contains("abc"){
          goInside = other.gameObject; 
     }
}

void OnTriggerExit2D (Collider2D other)
{

    if(other.gameObject.name.Contains("abc"){
          goInside = null; 
     }
}

Then in OnGUI() inside your button/key check if() you can check for a non-null value of goInside and do the Destroy() there. The other solution is to clear the liftClick flag after each frame. According to this diagram, you should be able to do it at the end of the frame (untested by me). So you could leave your OnTriggerStay2D() and then rewrite your OnGUI() code as follows:

private void OnGUI ()
 {
    Rect aRect = new Rect (0,0,20,20);
    if (GUI.Button (aRect, "") || Input.GetKeyDown ("left")) {
        leftClick = true;
        StartCoroutine(ClearStay());
    }
}

IEnumerator ClearStay() {
    yield return new WaitForEndOfFrame();
    leftClick = false;
}

Depending on the order of things, you might have to yield twice:

IEnumerator ClearStay() {
    yield return new WaitForEndOfFrame();
    yield return new WaitForEndOfFrame();
    leftClick = false;
}