Better approach to use OnTriggerStay2D [Solved]

Hi guys, I have a question, when creating this on my Player:

    void OnTriggerStay2D(Collider2D testBeam)
    {
        if (testBeam.CompareTag ("Finish"))
        {
            forceArea.gameObject.SetActive (true);
        }       
    }

The forceArea is working fine, but I though what would be inside a OnTriggerStay2D would be working until it’s not triggered anymore… working like a Boolean, I even tried to add a:

        Else {
            forceArea.gameObject.SetActive (false);
        }

but this is not working the way I wanted it either: the forceArea is staying active and is not getting back to false when the player is not anymore in the testBeam zone.

Can someone help me to better think the proper way to approach this please ?

Thx a lot.

OnTriggerStay2D() is only called when there is an overlap with another trigger. So, the way you have it set up, when the player’s collider leaves the forceArea, all of your code won’t even run, and the else block does nothing.

Instead, try using OnTriggerEnter2D() (called one time when the overlap starts) and OnTriggerExit2D() (called one time when the overlap ends) to change your boolean.

Ok, thx…
so, the OnTriggerEnter2D is pretty easy, but it don’t get the OnTriggerExit2d. For instance:

    void OnTriggerEnter2D(Collider2D testContact)
    {
        if (testContact.CompareTag ("PlayerFX"))
        {
            groundSmoke.gameObject.SetActive (true);
        }
    }

    void OnTriggerExit2d(Collider2D testExit)
    {
        if (testExit.CompareTag ("PlayerFX"))
        {
        groundSmoke.gameObject.SetActive (false);
        }
    }

The groundSmoke game objext is actually trigered when getting in contact, but the OnTriggerExit2d is not placing it back to false. I tried without a test. something like

    void OnTriggerExit2d(Collider2D testExit) 
        {
        groundSmoke.gameObject.SetActive (false);
        }
    }

But the result is the same, the groundSmoke is not getting back to false and is not disappearing.

I wrote something like this just to test, and this is making it disappears

    void FixedUpdate()
    {
        if (pressTestButton) 
        {
        groundSmoke.gameObject.SetActive (false);
         }
     }

Typo!

You used “OnTriggerExit2d()” instead of OnTriggerExit2D(), so Unity thinks you’re writing a custom function for something.

1 Like

Oups… :sweat_smile::p:smile:
Thx a lot!