Search Unity

OnTriggerEnter2d not working

Discussion in 'Physics' started by dusthound, Nov 3, 2018.

  1. dusthound

    dusthound

    Joined:
    Sep 18, 2018
    Posts:
    81
    I am trying to detect triggers between different objects. I do have a Rigidbody2D attached to all of the objects that are supposed to collide. The collision is detected if the enemy hits the bullet, but not if it hits the planet. here is my code:

    private void OnTriggerEnter2D(Collider2D collision)
    {
    if (collision.CompareTag("Laser"))
    {
    spawner.score = spawner.score + 1;
    Instantiate(particle, transform.position, transform.rotation);
    Destroy(gameObject);
    }else if (collision.CompareTag("planet"))
    {
    spawner.planethealth = spawner.planethealth - 1;
    Destroy(gameObject);
    }

    }
     
  2. SparrowsNest

    SparrowsNest

    Joined:
    Apr 6, 2017
    Posts:
    1,271
    1) use code tags
    2) use Debug.Log to see if the issue is the method is not called or the if statement doesn't execute
    3) try "Planet" instead of "planet", remember, it's case sensitive, compute doesn't know about lower/upper case, it's different stuff as far as his concerned.
     
  3. dusthound

    dusthound

    Joined:
    Sep 18, 2018
    Posts:
    81
    Thanks i will try that. i don't know how to use code tags.
     
  4. SparrowsNest

    SparrowsNest

    Joined:
    Apr 6, 2017
    Posts:
    1,271
    In the comment toolbar kajiiger, theres a page that has '<>' on it next the the words 'code:'
    Just click it and put the code there
     
  5. dusthound

    dusthound

    Joined:
    Sep 18, 2018
    Posts:
    81
    Ok thanks. I checked and it is the else if statement that is not being called. how do I fix this?
    Code (CSharp):
    1.  private void OnTriggerEnter2D(Collider2D collision)
    2.     {
    3.         Debug.Log("hit");
    4.         if (collision.CompareTag("Laser"))
    5.         {
    6.             spawner.score = spawner.score + 1;
    7.             Instantiate(particle, transform.position, transform.rotation);
    8.             Destroy(gameObject);
    9.         }else if (collision.CompareTag("planet"))
    10.         {
    11.             //This part not working
    12.             Debug.Log("Planet hit");//I never got this message in the console
    13.             spawner.planethealth = spawner.planethealth - 1;
    14.             Destroy(gameObject);
    15.         }
    16.        
    17.     }
     
  6. SparrowsNest

    SparrowsNest

    Joined:
    Apr 6, 2017
    Posts:
    1,271
     
  7. dusthound

    dusthound

    Joined:
    Sep 18, 2018
    Posts:
    81
    I will try that, but the tag is spelled "planet"