OnCollisionEnter and OnCollisionExit or OnCollisionStay method?

I used the OnCollisionEnter method to change the color of the wall to red when my player hits the wall and the OnCollisionExit method to restore the original color of the wall.

However, I would like to know if this is the corerect approach or the OnCollisionStay method is more appropriate for this purpose.

Thanks in advance.

Ivo

For your specific use case, I think Enter/Exit is correct. I can’t even think of an easy way to make it work if you use Stay because you need to be able to reset the color if the player is no longer ‘Staying’, and when will you do that?

I was thinking that the OnCollisionStay could replace the OnCollisionEnter and OnCollisionExit.

Although used for other purpose, here’s an example of the implementation of the OnCollisionStay: c# - "void OnCollisionStay()" not functioning properly? - Stack Overflow.

However, after reading the post and all the comments I have found that the OnCollisionStay does not trigger the event if the two bodies have already collided.

I know how it works. One of the problems in the linked code is that OnCollisionStay sets the isGrounded to true and Update sets it back to false, but Update runs far more frequent that OnCollisionStay because OnCollisionStay is a physics event and will only execute around 60 times per second, while Update can easily execute at over 500 times per second. You will likely find a lot of flickering in the color because it will be off for more frames than it will be on. It also doesn’t make real sense to continuously turn the color on and off. Set it on collision, reset it when the collision is over.
If the player could die while touching the wall the game would be over, but if it was something like an enemy, you’d need to just grab a reference in Enter, make sure it is still there in Stay, and then destroy the reference in Exit. I don’t believe the exit fires when an object is destroyed, so Stay would be a good place to check if it is still touching.

Thank you for the explanation. The behavior that you mentioned in the last part of your reply was what I was having in mind, not exactly for the example that you gave but for something similar.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms