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

Enemy taking damage problem

Discussion in 'Scripting' started by AV_Corey, May 11, 2016.

  1. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    So my player and enemies are setup just like in the image attached. My problem is that when the player's attack trigger enters the enemy it triggers the line of code for taking damage twice as there are two box colliders attached to the enemy gameObject.

    This is my code for checking if the player's attack trigger enters the enemy box collider:

    Code (CSharp):
    1.     void OnTriggerEnter2D(Collider2D other)
    2.     {
    3.         if (other.name == "AttackTrigger")
    4.         {
    5.             Debug.Log("Enemy take damage.");
    6.             TakeDamage();
    7.         }
    8.     }
    So yeah because I have two box colliders attached, and the script is checking for collisions to any box collider, it runs the TakeDamage() function twice when the player's attack trigger enters either collider.

    I'm sure I'm being an idiot and I'm fairly new to coding but could anyone help me out with a solution? :)
     

    Attached Files:

  2. mangax

    mangax

    Joined:
    Jul 17, 2013
    Posts:
    333
    Try having this enemy structure:

    (enemy gameobject)
    |__ child 1 Collider 1 (your script attached here)
    |__ child 2 Collider 2

    this way i think it will trigger for collider 01.. and ignores second one
     
  3. mangax

    mangax

    Joined:
    Jul 17, 2013
    Posts:
    333
    is your script at the parent (enemy) or the child?
     
  4. mangax

    mangax

    Joined:
    Jul 17, 2013
    Posts:
    333
    Another way and it must work..which is using unity layers.. to stop uneeded interactions between colliders.

    add your second collider ( the one you want to be ignored by attack collider) to a new layer.
    then go to your physics settings, on the matrix.. uncheck it's interaction with collider layer that is assigned to attack trigger collider.

    then it wouldn't detect, also this improves performance if you have many colliders in your scene that you never want your attack colliders interact with.
     
  5. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    I can't seem to get either of your solutions to work unfortunately :/
     
  6. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    I did however just find a solution that seems to be working fine :) Instead I attached a collider to the player that detects any enemies that enter and it seems to work as expected. Thank you for your help. <3