Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

OnTriggerEnter2D and OnTriggerExit2D trigger non-stop

Discussion in 'Scripting' started by nicklowkc1, Jan 8, 2021.

  1. nicklowkc1

    nicklowkc1

    Joined:
    Feb 27, 2019
    Posts:
    28
    I have two prefabs which they spawned at the same position. A has capsule collider2d attached and B has circle collider2d attached both set istrigger to true and also rigidbody2d attached.
    I gave both objects with different tag, and implement ontriggerenter2d and ontriggerexit2d inside object a.
    When i start the game and debugging, the ontriggerenter2d and ontriggerexit2d triggers every frame. However, if I dont implement either one of the trigger, it will just detect one time not every frame.

    Am I missing something here?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
    This behavior seems wrong. Try putting debug statements into your responders that tell you what they hit, something like:

    Code (csharp):
    1.     void OnTriggerEnter2D(Collider2D col)
    2.     {
    3.         Debug.Log( "Enter:" + name + " -> " + col.name);
    4.     }
    5.     void OnTriggerExit2D(Collider2D col)
    6.     {
    7.         Debug.Log( "Exit:" + name + " -> " + col.name);
    8.     }
     
  3. nicklowkc1

    nicklowkc1

    Joined:
    Feb 27, 2019
    Posts:
    28
    Hi, thank you for your reply.
    That's kind of weird, your code works well if I don't comparing tag in those methods.

    My code is like following:
    Code (CSharp):
    1. private void OnTriggerEnter2D(Collider2D collision)
    2.     {
    3.         if(collision.gameObject.CompareTag("MistakeCollider"))
    4.         {
    5.             Debug.Log( "Entering" );
    6.             collision.gameObject.GetComponent<CapsuleCollider2D>().enabled = false;          
    7.         }      
    8.     }
    9.  
    10.     private void OnTriggerExit2D(Collider2D collision)
    11.     {
    12.         if(collision.gameObject.CompareTag("MistakeCollider"))
    13.         {
    14.             Debug.Log( "Exit" );          
    15.             collision.gameObject.GetComponent<CapsuleCollider2D>().enabled = true;
    16.         }      
    17.     }
    Does it mean one of the collider should not be inside of another collider?