- Home /
How do I have OnCollisionEnter only called once per object?
I have an object with a wheel collider attached. When it hits a fixed wall, I want to decrease some of its health.
Psuedocode is:
OnCollisionEnter(Collision collision)
{
if(collision.gameobject is wall)
{
damageObject(currentVelocity);
}
}
The problem is, when my Car hits the wall and bounces off it, the function gets called more than once. Twice or thrice. I need it to run only once per object.
I thought of setting a timer to make the code only run once in a second. But there has to be a more elegant solution.
I thought of using a flag to make the code run only once, but where would I turn the flag off?
Edit: Ended up implementing a timer to call it once per second
Answer by Crystalline · May 31, 2015 at 09:56 AM
bool callOnce = new bool ();
OnCollisionEnter(Collision collision)
{
if(collision.gameobject is wall && !callOnce)
{
damageObject(currentVelocity);
callOnce = true;
}
}
It should work just fine.
callOnce would be false every time the method is called
$$anonymous$$y bad, move callOnce at the top of the script.
Your answer
![](https://koobas.hobune.stream/wayback/20220613200439im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Another Collision Question 3 Answers
OnCollision Works for one script but not the other? 2 Answers
How to detect collision without OnCollisionEnter or OnTriggerEnter? 1 Answer
Why the "Detonator Explosion Framework" from AssetStore don't render in compiled game? 0 Answers
Smooth movement for the block upon player collision,Smooth box movement 0 Answers