Search Unity

Stopping OnCollisionEnter from occurring too often

Discussion in 'Scripting' started by keithsoulasa, Sep 15, 2012.

  1. keithsoulasa

    keithsoulasa

    Joined:
    Feb 15, 2012
    Posts:
    2,126
    Whats the best way to stop an OnCollision even from occurring too often .

    Its a breakout like game, and I run the Alt() function every time the ball hits the paddle , right now i just jumps to 2 and then the game object destroys itself .


    Code (csharp):
    1.  
    2.     void OnCollisionEnter ()
    3.     {
    4.    
    5.     Alt();  
    6.    
    7.    
    8.     }
    9.    
    10.    
    11.     void Alt() {
    12.     ;
    13.         if( i == 0 ) {
    14.         Me.fillColor1 = ColorNew ;  
    15.             Me.RefreshMesh();
    16.     i ++ ;
    17.         }
    18.         if( i ==1 )
    19.         {
    20.             Me.fillColor1 = ColorB ;
    21.         i++;   
    22.         Me.RefreshMesh();
    23.         }
    24.        
    25.         if(i== 2 ) {
    26.            
    27.         Destroy(gameObject);
    28.        
    29.         }
    30.        
    31.     }
    32.  
    I could do this with Couritines , but I'd like to know if their was a clearer way of doing this .
     
  2. arkon

    arkon

    Joined:
    Jun 27, 2011
    Posts:
    1,122
    I think it's because the ball hasn't moved out of the collision box by the time it gets called again. I solved this problem by seting a timer to say 1/10 th of a second after the 1st hit and just returning from your collision routine if the time hasn't passed yet.

    Another way is to set a flag on entry and clear the flag on collision exit, so don't process the collision if the flag is still set.