Search Unity

Overlapping colliders adding force to eachother on initial frame when ignore is set

Discussion in 'Physics' started by BigRookGames, Jul 10, 2018.

  1. BigRookGames

    BigRookGames

    Joined:
    Nov 24, 2014
    Posts:
    330
    I have an issue where right when an object is instantiated, it acts on the objects around it for the initial frame, and pushed them away, even when the object has a script that has:
    Code (CSharp):
    1. protected void OnCollisionEnter(Collision collision)
    2.     {
    3.             //checks to see if the layer is in the collision layers, if not it runs the ignore
    4.             if (((1 << collision.gameObject.layer) & collisionLayers) == 0)
    5.             {
    6.                 //It wasn't in the layer
    7.                 Physics.IgnoreCollision(collision.collider, m_Collider);
    8.             }
    9.     }
    Where m_colliders is populated as:
    Code (CSharp):
    1. var colliders = GetComponents<Collider>();
    2.         for (int i = 0; i < colliders.Length; ++i)
    3.         {
    4.             if (colliders[i].isTrigger)
    5.             {
    6.                 m_Trigger = colliders[i];
    7.             }
    8.             else
    9.             {
    10.                 m_Collider = colliders[i];
    11.             }
    12.         }
    If i insert 2 objects at the same time it pushes them away from each other with a lot of force, but both are in the collision layer that should be ignored.

    Is this expected? does it have something to do with the time it takes the script to initialize on the object after the initial collision detection is calculated?

    Any help is greatly appreciated.
     
  2. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,510
    When OnCollisionEnter is called the collision has already been detected and processed. Thus, further collisions will be ignored, but not the first collision that triggered the event.

    A possible solution is to instantiate objects with trigger colliders only, then listen to the OnTriggerEnter method. Then you may call Physics.IgnoreCollisions and then turn the colliders into non-trigger colliders. Note that if OnTriggerEnter is not called (i.e. there wasn't any nearby object) then you should explicitly convert the triggers to colliders the next frame after instancing.
     
    BigRookGames likes this.
  3. BigRookGames

    BigRookGames

    Joined:
    Nov 24, 2014
    Posts:
    330
    Thanks, I understand it now.

    I was thinking roughly the same solution to get around the issue, and now it is apparent that it is working properly which is good to know.

    Thanks a lot, very helpful info.
     
    Edy likes this.