- Home /
OnTrigger bullet with multiple colliders on enemy
Hi, My enemies use multiple colliders, one to detect the player and one for detecting when hit with bullets but I cant figure out how to make the bullets pass through the first collider without triggering the damage and destroying the bullets. Thanks.
Bullet Code
public GameObject hitEffect; public int damage = 40;
void OnTriggerEnter2D(Collider2D collision)
{
Enemy enemy = collision.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
GameObject effect = Instantiate(hitEffect, transform.position, Quaternion.identity);
Destroy(effect, 0.22f);
Destroy(gameObject);
}
Enemy Code
private void OnCollisionStay2D(Collision2D other) { if (other.gameObject.tag == "Player") { if (attackSpeed <= canAttack) { other.gameObject.GetComponent().UpdateHealth(-attackDamage); canAttack = 0f; } else { canAttack += Time.deltaTime; } } }
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
target = other.transform;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.tag != "Player")
{
return;
}
target = null;
}
public void TakeDamage (int damage)
{
health -= damage;
if (health <= 0)
{
Die();
}
}
void Die ()
{
GameObject effect = Instantiate(deathEffect, transform.position, Quaternion.identity);
Destroy(effect, 0.22f);
Destroy(gameObject);
}
Could you please share screenshot of the inspector in Unity Editor for the enemy gameobject. Just want more clarity whether enemy has two colliders on it or has nested colliders.
As you are using trigger for collisions the bullet will pass through both colliders. If you have nested colliders then you can check which gameobject did you collide the parent or the child and based on that info you can implement your logic.
Answer by sharatachary · May 15 at 02:57 AM
Modify the bullet code:
void OnTriggerEnter2D(Collider2D collision)
{
Enemy enemy = collision.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
GameObject effect = Instantiate(hitEffect, transform.position, Quaternion.identity);
Destroy(effect, 0.22f);
Destroy(gameObject);
}
}
So bullet will only be destroyed when it hits an enemy.
Thankyou very much this worked perfectly, I can't believe the solution was so simple I feel like an idiot. Regardless Thankyou.
Your answer
Follow this Question
Related Questions
OnCollisionEnter2D ignores Z axis!,OnCollissionEnter2D ignores z axis. 0 Answers
I need help with a top down 2d shooter 3 Answers
Have bullets be destroyed when they collide with ANY collider 0 Answers
Transform collider not detecting collision on rigidbody collider 2 Answers
OnCollisionEnter() not getting called between two rigid bodies 3 Answers