Unity Destroy(gameObject) kills parent object and collision trigger on multiple colliders

StackOverflow https://stackoverflow.com/questions/22367865

  •  13-06-2023
  •  | 
  •  

Pergunta

I have a script where an arrow is supposed to disappear when colliding with an enemy. I use

    function OnTriggerEnter2D(coll: Collider2D) {
        coll.gameObject.BroadcastMessage("ApplyDamage", 10);
        Destroy (gameObject);
}

The first problem is that when the game object is destroyed, I get an error and says The object of type 'Transform' has been destroyed but you are still trying to access it. It seems because the parent object is destroyed. I also have another problem. When I have enemies stacked on top of each in 2D they stop at a cretain location and sometimes there's more than 1 enemy sharing the same collision area. One arrow will do damage to all of the enemies in the same spot instead of just one enemy in the same spot.

    var health = 10;

    function ApplyDamage (damage : float) {

    health -= damage;

    if ( health <= 0) {
    Destroy(gameObject);
    }
}
Foi útil?

Solução

For your second question:

The arrow collider will trigger the collision in all colliders that it touches, that's the appropriate behaviour. If you want to make the arrow only collide with one enemy than you should create a script on the arrow and use its OnTrigger/OnCollision to disable its collider.

Outras dicas

It seems because the parent object is destroyed.

When did the parent object get destroyed? If it was destroyed before

Destroy (gameObject);

Then you do not need to destroy the gameobject as it will automatically be destroyed when the parent is destroyed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top