1

I'm making a 3rd person shooter and currently working on projectiles. My projectiles are rigidbodies, and when they are instantiated, they instantiate a geometry according to the weapon used. Anyway, I'm trying to make the projectile destroy itself when it collides but it don't works. Here's the code:

void Update()
{
    if(Physics.CheckSphere(transform.position, 0.5f)) {
        
        Collider[] hitted = Physics.OverlapSphere(transform.position, 0.5f, enemy);
        foreach(var hit in hitted) {
            hit.transform.gameObject.GetComponent<BasicAI>().damage((int)Random.Range(damageAmount[0], damageAmount[1]), sender.transform);
        }

        Destroy(gameObject);
    }        
}

Hope you can help me!

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
SquiDev
  • 11
  • 2
  • This should work. Do you have any errors in the console? The only reason for it not to work that I can think of, is if the `GetComponent()` in your inner loop returns null, which would then cause an error and Detroy won't be executed at all. – Bart Jun 17 '22 at 13:36
  • You're right thanks ! i just added "if(hit.transform.gameObject.GetComponent() != null)" – SquiDev Jun 17 '22 at 13:50

1 Answers1

0

The call to Destroy(gameObject) should work. The dangerous line that stands out to me is

hit.transform.gameObject.GetComponent<BasicAI>().damage((int)Random.Range(damageAmount[0], damageAmount[1]), sender.transform);

If the gameObject doesn't have a BasicAI component, you'll run into a NullReferenceException. This in Unity won't crash your game right there and then. It will however no longer execute the rest of the Update(), and show you an error in the console.

It's tempting to make assumptions about an object having a particular component, upon which you can then call one of its methods. It's probably better to be a bit more defensive. For example, change it to

foreach(var hit in hitted) {
    var basicAI = hit.transform.gameObject.GetComponent<BasicAI>();
    if(basicAI != null)
    {
        basicAI.damage((int)Random.Range(damageAmount[0], damageAmount[1]), sender.transform);
    }
    else
    {
        Debug.LogError("Expected GameObject to have a BasicAI component, but it didn't!");
    }
}

But even if you decide not to do that, pay close attention to your console whenever you encounter strange behaviour like this.

Bart
  • 19,692
  • 7
  • 68
  • 77
  • Yes but you forget that all the colliders in hitted have the layer "enemy", and in my scene, all enemies have this script. Collider[] hitted = Physics.OverlapSphere(transform.position, 0.5f, enemy); <-- Here is the layermask. Anyway, now with a simple if statement it works how i expected so it's fine , Thanks ! – SquiDev Jun 17 '22 at 14:04