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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question OnTriggerEnter2D is called twice

Discussion in 'Scripting' started by AlexdV, Apr 23, 2022.

  1. AlexdV

    AlexdV

    Joined:
    Apr 20, 2022
    Posts:
    2
    Hello,
    i have a bug that some times OnTriggerEnter2D is called twice, so enemy get double damage.
    There is no second bullet spawning at a same time. I change their names with index.

    Bullet code part:
    Code (CSharp):
    1.  private void OnTriggerEnter2D(Collider2D other)
    2.     {
    3.         if ((other.tag == "Enemy"||other.tag == "Player")& other.tag !=gameObject.tag)
    4.         {
    5.            
    6.             if (other.tag == "Enemy")
    7.             {
    8.                 print("Hit!");
    9.                 other.GetComponent<EnemyConfig>().DamageTaken(damage);
    10.             }
    11.             else
    12.             {
    13.                 PlayerConfig.HealsUpdate(-damage);
    14.             }
    15.             Destroy(gameObject);
    16.             print("object" +gameObject.name +" destroyed");
    17.         }
    18.     }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,621
    This'll be because it hits two colliders or there are two colliders on this GameObject that are either triggers or hit a trigger.

    Simply debug it beyond just printing "hit". "Other" will tell you what it's hitting and you'll know if there are two colliders on the GameObject this script is on.
     
    AlexdV likes this.
  3. AlexdV

    AlexdV

    Joined:
    Apr 20, 2022
    Posts:
    2
    So it really was because of two box colliders on enemy gameObject. But what can i do if i need one normal collider and one trigger (trigger is full size and normal collider at feet)? how cani ignore a normal one?
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,621
    What's a "normal" one? You mean non-trigger? A non-trigger produces a OnCollisionEnter2D so it's a completely different callback. You can also place them on different GameObject, each with their own script if you wish.