Ship will not be destroyed when hit by lasers

that’s y code
void OnTriggerEnter2D(Collider2D collision)
{
Laser missile = gameObject.GetComponent();

        missile =gameObject.GetComponent<Laser>();
        if (missile)
        {
            health -= missile.GetDamage();
            Debug.Log("Hit by a laser");
            missile.Hit();
        }
        if (health <= 0)
        {
            Die();
        }
    }
    void Die()
    {
        Destroy(gameObject);
    }
}

but somehow my ship will not be destroyed .
my ship is Trigger and enemy laser collide with my ship on the matrix .
i read other people’s question too but the error is not the same

1 Like

Hi Francesco,

As far as I can see you are not checking if what collided with the ship is a missile. You are checking if the ship has the component Laser.

Try:

    void OnTriggerEnter2D(Collider2D collision)
    {
        Laser missile = collision.gameObject.GetComponent<Laser>();
        if (missile)
        {
            health -= missile.GetDamage();
            Debug.Log("Hit by a laser");
            missile.Hit();
        }
        if (health <= 0)
        {
            Die();
        }
    }
    void Die()
    {
        Destroy(gameObject);
    }

1 Like

now it works … i tried with collision.gameobject but it said that there was an error but with your code is working

2 Likes

Glad I could help.

gameObject accesses the GameObject to which this script is attached to: the ship. The collision attribute in that method


is the other object’s collider that just entered the collider of the ship when the method was triggered.

So basically you are checking if the other game object has the Laser component to know if it’s a projectile.

You need


, because the method “receives” the Collider2D component of the other Object.

Collider2D does not implement a GetComponent method, since it is a component in itself and has no components. Game objects contain components and the GameObject class implements GetComponent.
So by doing the above, you access the GameObject to which the received Collider2D is attached to.

1 Like

Privacy & Terms