Disable a destroy when called in OnTriggerExit2D?

Hi guys.

Im having trouble with implementing some code.
Hoping you can “help” or “clear” things up for me.

Firstly. I have a 2d collider that is the boundary for my sidescolling level. Now what needs to happen is the following.

When the player exit the collider or in other words does not collide with the boundary collider anymore ( using OnTriggerExit2D), the player will be killed/destroyed within a float delay value of 5 seconds.

Now this is all good and well (working) with the following code.

void OnTriggerExit2D(Collider2D other) 
{   
      If(other.gameObject.tag == "Player")
      {
      Destroy(Player, 5f);   
      }
 }

The player gets destroyed after 5 seconds out of the boundary.

Now my problem is. Once that piece of code is enabled, I can not disable it once the player returns into the collider. Player still gets destroyed even if I null the destroy function in OnTriggerEnter2D.

Please guys. Im begging you. Been sitting on this for a week now and im out of ideas.

Thanks in advance for your help and patience.

I would suggest a few things,

  1. Because you know who your player is in game I would set it in a variable look by tag.

    if(other.gameObject.name == “Player”)

  2. Don’t rely on the Destroy timer, you should be toggling a bool and a timer

    bool isPlayerOutOfBounds = false;
    

    //OnTriggerExit2D
    if(other.gameObject.name == “Player”)
    isPlayerOutOfBounds = True;

    //OnTriggerStay2D
    if(other.gameObject.name == “Player”)
    isPlayerOutOfBounds = False;

    Update()
    {
    if(isPlayerOutOfBounds)
    //startTimer
    if(Timer >= 5)
    Destroy(Player);
    else
    Timer = 0;
    }