- Home /
Question by
haxorbird · Jul 10, 2020 at 10:14 AM ·
c#unity 2dcollision detectioncollision2d
OnCollisionEnter2D is not working when an object tagged "Enemy" is not present in the game.
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;
}
}
Comment