简体   繁体   English

在 Unity 3D 中,为什么 Destroy(gameObject) 在这里不起作用?

[英]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.Destroy(gameObject)的调用应该可以工作。 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.如果游戏对象没有BasicAI组件,您将遇到 NullReferenceException。 This in Unity won't crash your game right there and then.这在 Unity 中不会立即使您的游戏崩溃。 It will however no longer execute the rest of the Update() , and show you an error in the console.但是,它将不再执行Update()的其余部分,并在控制台中显示错误。

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.但是,即使您决定不这样做,只要您遇到此类奇怪的行为,请密切注意您的控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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