Enemy lasers do not register hits on player ship

Hello,
For some reason, lasers shot by enemies do not register hits on my player ship. I have copied and adjusted the code from the EnemyBehavior script into my PlayerContorller Script, added the heatlh variable, and even made sure the player ship had rigidbody2D and Polygon Collider (with checked Trigger box). The code does not report any bugs or errors, but it does not log a hit nor destroys the player’s ship. What could be the reason?

public float health = 250;

void OnTriggerEnter2D(Collider2D collider)
{

    Projectile shot = collider.gameObject.GetComponent<Projectile>();
    if (shot)
    {
        Debug.Log("Hit by a projectile");
        health -= shot.GetDamage();
        shot.Hit();

        if (health <= 0)
        {
            Destroy(gameObject);


        }
        

    }


}

Hi @Pixelrave,

A little more challenging with only a snippet of the code available in this scenario, but the first thing we could try would be to determine if your OnTriggerEnter2D code is being reached. You are already trying to get the Projectile component on the colliding GameObject, I’ll assume it actually attached, but what we could do is add this to your if statement;

void OnTriggerEnter2D(Collider2D collider)
{

    Projectile shot = collider.gameObject.GetComponent<Projectile>();
    if (shot)
    {
        Debug.Log("Hit by a projectile");
        health -= shot.GetDamage();
        shot.Hit();

        if (health <= 0)
        {
            Destroy(gameObject);


        }
    }
    else
    {
        Debug.Log("Shot was null");
    }    

}

So, if something now triggers the OnTriggerEnter2D method, you should definitely get something output to the console.

Run the code and lets see what happens.

Hello Rob,
I took a long time to try your suggestion, I have been very busy at work before the Holidays. Your suggestion helped me, it was returning null and I noticed that my enemy laser did not have the projectile script attached to it. Somehow I believed that it did, but I realized that I had created the enemy laser way before I started this topic.
Thank You!

1 Like

Hi,

Really pleased to hear the above was of use and glad to hear you have resolved the issue and can move forward again. Well done :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms