简体   繁体   中英

In Unity 3D, Why Destroy(gameObject) doesn't work here?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM