Matching OnTriggerStay to OnTriggerEnter

I am initializing some stuff in OnTriggerEnter, then I want to use that stuff in OnTriggerStay.

But these run when any object collides, so my OnTriggerEnter would run again when another thing collides, and overwrite the initialized stuff.

So I want to make it so each OnTriggerEnter matches to an OnTriggerStay.

I tried this:

Starting a coroutine on OnTriggerEnter, which runs the OnTriggerStay code.

OnTriggerExit, I set a Collider variable called exitedCollider to the collider that is passed in. Then in the coroutine, its while loop checks if its collider is equal to the exitedCollider. If it is, then it ends the loop.

I also need to check if the collider is already running in a coroutine before I start it, so I do that by setting and checking the name of the collider.

It works, but it will bug out sometimes, if it hits multiple colliders at once. I think OnTriggerExit gets called multiple times in one frame, and it causes my coroutine to miss some of the colliders that exited.

So I added each exitedCollider to a list, then check the whole list in my coroutine, and clear it in FixedUpdate, and now it works.

But I’m wondering if there is some better way of doing it.

This is my code:

private void OnTriggerEnter()
{
if (collision.name!="a") {

            IEnumerator thing;

         thing = triggerStay(collision);

            Debug.Log(collision+ "Entered");

            StartCoroutine(thing); }
}
private void OnTriggerExit(Collider collision)
    {
        //Debug.Log(exitedCollider+ "Exited");
        exitedColliders.Add(collision);}
private void FixedUpdate()
    {exitedColliders.Clear();}
   IEnumerator triggerStay(Collider collider)
    {
        collider.name="a";

        while (checkList(exitedColliders, collider)) { Debug.Log("inside");

        yield return new WaitForFixedUpdate(); } collider.name="b";
    }




    bool checkList(List<Collider> list, Collider collider)
    {
        for (int i=0; i<list.Count; i++)
        {
            if (list[i]==collider) {return false;}
        }
        return true;

    }

Seems like you’re trying to do something like this?

List<Collider> collisions = new List<Collider>();

void OnTriggerEnter ( Collider collider ) {
    if( !collisions.Contains( collider ) ) {
        collisions.Add( collider );
    }
}

void OnTriggerExit ( Collider collider ) {
    collisions.Remove( collider );
}

void FixedUpdate () {
    foreach( var collider in collisions ) {
        // do something with collider
    }
}
1 Like

i think so, thnx