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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

My arrow hits many colliders instead fo one.

Discussion in '2D' started by tkaczu, Jan 6, 2018.

  1. tkaczu

    tkaczu

    Joined:
    Aug 8, 2013
    Posts:
    6
    Hi, here is my problem.

    I have a 2d platform game.
    I have two identical gameobjects with colliders, they are moving from right to the left while I am shooting at them.
    There is a place where all enemies have to stop. And there are cases when they are in the same position with the same colliders. So we practically see them as one object.
    And in this case when my bullets hit them, all enemies die.
    What I need to do is choose one of them and kill only one and I have no idea how to do that.

    Code (CSharp):
    1. Private void OnCollisionEnter2D(Collision2D hit)
    2.     {
    3.         if (hit.transform.tag == "bullet")
    4.         {
    5.                 Invoke("destroyy", 4);
    6.  
    7.         }
    8.     }
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You could add a script on your arrow.
    Code (csharp):
    1.  
    2. public bool hasHit = false;
    3.  
    Now, your collision script can be changed....
    Code (csharp):
    1.  
    2. void OnCollisionEnter2D(Collision2D hit) {
    3.    ArrowScript ascript = hit.transform.GetComponent<ArrowScript>();
    4.    if(ascript != null) {
    5.        if(!ascript.hasHit) {
    6.               ascript.hasHit = true;
    7.               Invoke("destroyy", 4);
    8.            }
    9.      }
    10.  }
    11.  
    That should make it able to only hit one. :)
     
    tkaczu likes this.
  3. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,955
    if disable collider, or destroy the arrow at OnCollisionEnter2D() would that be fast enough, that it doesn't trigger collisions on others?
     
  4. tkaczu

    tkaczu

    Joined:
    Aug 8, 2013
    Posts:
    6
    Sadly no :(


    Thank you Methos5k, Now everything works perfectly fine.
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You're welcome. Glad I could help.