I’m working on a little game project and been following different youtube tutorials but I’m kinda stuck now. In game there is an enemy with ranged attack, if you want to kill it you need to throw a rock on it. Everything works as it should but if player comes in ranged collider of an enemy with rock there is an error. Howevere if player avoids ranged collider and drops a rock onto an enemy it will be destroyed (no error appers). Here’s the script i’m using:
private bool PlayerInSight()
{
RaycastHit2D hit = Physics2D.BoxCast(boxCollider.bounds.center + transform.right * range * transform.localScale.x * colliderDistance,
new Vector3(boxCollider.bounds.size.x * range, boxCollider.bounds.size.y, boxCollider.bounds.size.z), 0, Vector2.left, 0, playerLayer);
if (hit.collider != null)
playerHealth = hit.transform.GetComponent<PlayerHealth>();
return hit.collider != null;
}
private void DamagePlayer()
{
if (PlayerInSight())
playerHealth.TakeDamage(damage);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag.Equals("rock"))
{
Destroy(gameObject);
}
}
public void TakenDamage(float damageAmount)
{
health -= damageAmount;
if (health <= 0)
{
Destroy(gameObject);
}
}