Search code examples
c#unity-game-enginedestroygameobject

Unity - GameObject won't destroyed when hit a prefab


In the game you controll a ball (Sphere) and two types of boxes falling down: deathCube and goldCube. When the Sphere hit the DeathCube, then the Sphere is destroyt, but it not get destroyed and I don't know why. The cubes are prefabs and they have a tag(DeathCube, GoldCube).

    void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "DeathCube") 
    {
        Destroy (gameObject);
    }
}   

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "GoldCube") 
    {
        gold++;
    }
}   

If the Sphere hit the goldCube you get points, but this doesn't work too.


Solution

  • If you don't have a rigidbody attached to at least one of the objects in the collision (ball or cube), then the trigger event won't be initiated.

    From the documentation:

    Notes: Trigger events are only sent if one of the colliders also has a rigidbody attached

    Source: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter.html