Koska
Koska

Reputation: 131

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.

Upvotes: 1

Views: 2303

Answers (2)

Doh09
Doh09

Reputation: 2385

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

Upvotes: 1

Daxtron2
Daxtron2

Reputation: 1309

Try merging the two OnTriggerEnter's into one.

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

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

I believe that the second one is overriding the first, never allowing the Destroy() to be called. I would've assumed the compiler would throw an error with this, but you don't seem to have indicated that.

Upvotes: 2

Related Questions