- Home /
OnCollisionEnter2D is not working when an object tagged "Enemy" is not present.
Three object are capable of hurting my player character. Patrolling enemy, Firing enemy and onGround spikes tagged "hurting". But my character is not taking damage when there is no enemy in the scene or my character has killed the enemy. This is my code:
void OnCollisionEnter2D(Collision2D col)
{
GameObject enemy1 = GameObject.Find("Enemy1");
Enemy1 enemyOne = enemy1.GetComponent<Enemy1>();
if (col.gameObject.tag.Equals("Enemy"))
{
StartCoroutine(Flash());
health -= 1;
if (facingRight && enemyOne.movingRight == false)
{
rb.AddForce(Vector2.left * knockBack + Vector2.up * knockBack);
}
else if (!facingRight && enemyOne.movingRight == true)
{
rb.AddForce(Vector2.left * knockBack + Vector2.up * knockBack);
}
else if (!facingRight && enemyOne.movingRight == true)
{
rb.AddForce(Vector2.right * knockBack + Vector2.up * knockBack);
}
else if (facingRight && enemyOne.movingRight == true)
{
rb.AddForce(Vector2.right * knockBack + Vector2.up * knockBack);
}
}
else if (col.gameObject.tag.Equals("hurting"))
{
StartCoroutine(Flash());
health -= 1;
if (facingRight)
{
rb.AddForce(Vector2.left * hurtingKnockBack + Vector2.up * 400);
}
if (!facingRight)
{
rb.AddForce(Vector2.right * hurtingKnockBack + Vector2.up * 400);
}
}
else if (col.gameObject.tag.Equals("enemyBullet"))
{
StartCoroutine(Flash());
health -= 1;
}
}
Answer by TheAwesomeLyfe · Jul 09, 2020 at 11:46 AM
@haxorbird Does your "Enemy" Game Object is properly tagged as Enemy and has it's own collider attached to it? Without those two OnCollisionEnter() won't fire, Especially if there's no collider on the opposing game object. Also Ensure your player Game object it has it's collider as well. This same rule applies to your other objects that will damage the player.
Hope this Solves your problem.
Answer by haxorbird · Jul 10, 2020 at 02:25 PM
@TheAwesomeLyfe I solved the problem by excluding this from the function:
GameObject enemy1 = GameObject.Find("Enemy1");
Enemy1 enemyOne = enemy1.GetComponent<Enemy1>();
The function was being dependent of Enemy1. To check the facing of enemy, I just made a bool in the script assigned to enemy and then reference it in my players' script. Thanks.