OnTriggerStay or OnTriggerEnter ?

Hello Coders!

So I’m having a small issue here. I’ve got a script to make a timed dissolve of any mesh render. It works well.

I’ve now decided I’d like to trigger it when my player enters the trigger. It works…but not how I want it.

When I use OnTriggerEnter, it only does a small percentage of the dissolve process ever time the player enters.

When I use OnTriggerStay, it does the entire dissolve of the mesh render but then the mesh reappears and it does it again…and again…as long as the players stays in the trigger !

So my question is : What should I be using and is there a way to stop the OnTriggerStay after the dissolve is complete?

Here’s the code:

	void OnTriggerEnter(Collider other)
	{
		if (other.tag == "Player")
		{

        m_fTime += Time.deltaTime * m_fDestruktionSpeed;
        if (m_fTime >= 1.5f)
            m_fTime = 0;
        m_Mat.SetFloat("_Amount", m_fTime);
	}
}
}

And so really I’d like this part of the code

    m_fTime += Time.deltaTime * m_fDestruktionSpeed;
            if (m_fTime >= 1.5f)
                m_fTime = 0;
            m_Mat.SetFloat("_Amount", m_fTime);

to loop only a certain amount of time after the player has entered the trigger (whether he exits the trigger or stays in it.

Thanks! :slight_smile:

Arnaud

I’d go with @meat5000’s suggestion on this.

If you’re not comfortable with coroutines, you could flip an isDissolving boolean to true and run your dissolve function in your Update() loop instead… but coroutines are wonderful, magical things, so I would absolutely learn how to use them if you can’t yet.

It looks like the reason your dissolve starts again is probably due to the fact that you’re setting m_fTime back to 0f when it reaches about 1.5f (that’s just a guess based on what I can see, I don’t know exactly what _Amount controls), so how about ending the dissolve function at that point?

You’ll probably want to track whether each object is solid, dissolving or dissolved anyway, so you could use an enum : move the enum from solid to dissolving OnTriggerEnter() if the enum is solid, then either start your coroutine or wrap the dissolution in an if(myEnum == dissolutionEnum.dissolving){} clause in your Update() loop.
In either case, run your dissolution until m_fTime >= 0f then move your enum from dissolving to dissolved and step out of the coroutine or the if{} clause.