Search Unity

I need some Help.

Discussion in 'Scripting' started by Aqu1l0n, Jul 20, 2017.

  1. Aqu1l0n

    Aqu1l0n

    Joined:
    Jul 20, 2017
    Posts:
    4
    In my Game i want to make it so that when the Laser hits the Asteroid that the LaserProjectile gets destroyed by the Asteroid. I dont want to attatch the Destroy function in the Laser because there will be enemys and if i atttatch the Destroy function on my laser they will always be oneshot. I placed these lines of Code on my Asteroids but the Laser doesnt get Destroyed.
    Laser has a BoxCollider2D and a Rigidbody2D.
    The Asteroids got a PolygonCollider2D and a Rigidbosy2D.


    void OnCollisionEnter2D(Collision2D col){

    if (col.gameObject.tag == "Laser") {

    Destroy (gameObject);
    }
    }
     
  2. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    it looks correct to me. Can you though in a Debug.Log("OnCollisionEnter"); to verify that the OnCollisionEnter is being used.

    Verify that the Colliders is not set to a trigger.
     
  3. Aqu1l0n

    Aqu1l0n

    Joined:
    Jul 20, 2017
    Posts:
    4
    I tryed it but it didnt Log anything. Do you have any clue what i can do.
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Wait, so you want to destroy the laser and not just the asteroid?

    So...

    Destroy(col.gameObject); ? Right now you're destroying the asteroid, but not doing anything with the laser.
     
  5. Aqu1l0n

    Aqu1l0n

    Joined:
    Jul 20, 2017
    Posts:
    4
    So how can i destroy the laser?
    I am new to programming :oops:
     
  6. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    I just showed you how. Add that code above the code to destroy the asteroid. Or replace it if you don't want to destroy the asteroid.
     
  7. Aqu1l0n

    Aqu1l0n

    Joined:
    Jul 20, 2017
    Posts:
    4
    Okey i want to destroy the laser but not the asteroid and if the playershit collides with the asteroid it shouldnt get destroyed.

    EDIT.

    I forgot to add the Tag to my Laser now it works perfectly fine :)
    Sorry if I caused some trouble.
     
  8. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    it should be this to destroy the laser

    Code (CSharp):
    1. void OnCollisionEnter2D(Collision2D col)
    2. {
    3.     Debug.Log("Collision with " + col.gameObject.name);
    4.     if (col.gameObject.tag == "Laser")
    5.     {
    6.       Destroy (col.gameObject);
    7.     }
    8. }