在 Unity 中破坏和奇怪的行为(多个克隆)

Destroy in Unity and weird behaviors ( multiple clones )

我想创造一个像地雷一样的东西,这意味着会有一个物体,当有人踩到它时,就会发生爆炸,踩到的物体会受到伤害。这部分效果很好,我已经能够自己弄清楚这种行为。

踩到地雷后,物体会自行销毁。因此它创建的 "explosion" 保留在这里。更奇怪的是,地雷创造了这次爆炸的多个分身。这是代码

using UnityEngine;
using System.Collections;

public class Mine : MonoBehaviour {

    Transform playerT;
    GameObject itself;

    // Use this for initialization
    void  Awake() {
        playerT = GameObject.FindGameObjectWithTag ("Player").transform;
    }


    void OnTriggerEnter(Collider other) 
    {
        if (other.gameObject.tag == "Monster") {

            EnemyHealth enemyHeatlh = other.GetComponent<EnemyHealth> ();
            enemyHeatlh.Death ();

            PyroExplode Pyro = gameObject.AddComponent("PyroExplode") as PyroExplode;

            Pyro.setTransform(transform);
            Pyro.Generate ();

            Destroy (Pyro.gameObject, 1.6f);
            Destroy (this.gameObject, 1.6f);

        }
    }
}

在这段代码中,我实例化了一个新的 PyroExplode,设置了它的转换属性并调用了方法 Generate()。这是 Generate() 方法:

public void Generate(){ 
    Instantiate ( Resources.Load ("Pyro1"), mineTransform.position, mineTransform.rotation);
}

这将加载一个带有动画、球体碰撞器和附加脚本的预制件(脚本正在渲染爆炸效果)。所以现在这就是当有人踩到地雷时会发生的事情!

创建了多个克隆。我一开始以为是因为怪物还在和地雷碰撞,于是想起了OnTriggerEnter()事件。我试图在我的 OnTriggerEnter() 中将我的对撞机的半径设置为 0,这样它就不会再与其他任何东西发生碰撞,但它无济于事。另外,如您所见,火焰兵并没有被摧毁。我试图在 PyroExplode class 中调用 Destroy 以查看它是否会有所作为,但它没有。

所以这是我的 2 个问题:

1- 为什么它没有被销毁?
2- 为什么踩到地雷时会有不止 1 个火焰兵?

我认为既然你有一个球体对撞机,另一个物体在进入时会在很多点上发生碰撞。考虑两个球体发生碰撞,为了让引擎报告碰撞,这两个项目需要重叠。如果您有两个至少有 4 个接触点的球体,则这四个球体要求进入。与立方体相同。如果对撞机比较复杂,调用的次数可能会更多

您可以尝试阻止多次调用:

private bool sentinel = false;
void OnTriggerEnter(Collider col){
    if(this.sentinel == true){ return; }
    this.sentinel = true;
    // rest of the code
}