My RPG Rocket Wont delete itself due to get component script

So I think this is my first posting here in a while, but I have an issue with my code for my rpg rocket.
So the issues stems from the fact that when I shoot and it touches anything it gets destroyed. However when i implement the code to deal damage to my enemies suddenly the rocket doesnt destroy itself? But it works when I delete that line of code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class rpgRocketdestruction : MonoBehaviour
{
    public LayerMask enemylayers;
    public float explosionradius;
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
       
    }
    void OnDrawGizmosSelected()
    {
        Gizmos.DrawWireSphere(gameObject.transform.position, explosionradius); //for me to see the radius of the explosion
    }
    void OnCollisionEnter(Collision collision)
    {
        Collider[] enemiesinrange;
        enemiesinrange = Physics.OverlapSphere(gameObject.transform.position, explosionradius, enemylayers); //adds anything with the enemylayers into array so only enemies
        foreach (Collider enemy in enemiesinrange)
        {
            Debug.Log("we hit " + enemy.name);
            enemy.GetComponent<Enemy>().TakeDamage(10);//the line that causes my issue
        }
        Destroy(gameObject);
    }

}

I would guess there is not always an ‘Enemy’ script attached to the ‘collision’ object and an error is thrown. To check this, enable ‘Error Pause’ in the console. Or do a check that enemy.GetComponent() is not null before calling TakeDamage.

1 Like

Yeah you were right, i added a check for the enemy.getcomponent and it now works

thank you very much

As an aside, a more-general approach to this which lets you damage many different objects all with the same “TakeDamage(10)” code involves using interfaces.

Using Interfaces in Unity3D:

https://discussions.unity.com/t/797745/2

https://discussions.unity.com/t/807699/2

Check Youtube for other tutorials about interfaces and working in Unity3D. It’s a pretty powerful combination.