How would I make my script detect if a component exists and if it doesn’t do something. for example: if (enemy.GetComponent = null). I would want to implement that in the attack function. if the enemy component doesn’t exist, damage the Houn_health. I would like to do that so I don’t get a error saying that the component is null.
This is my code:
public class Playercombat : MonoBehaviour
{
public Animator animator;
public Transform attackPoint;
public float attackRange = 0.5f;
public LayerMask enemyLayers;
public int attackDamage = 40;
void start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Attack();
}
}
void Attack()
{
animator.SetTrigger("Attack");
Collider2D[]hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
foreach(Collider2D enemy in hitEnemies)
{
enemy.GetComponent<enemy>().TakeDamage(attackDamage);
enemy.GetComponent<Houn_health>().TakeDamage(attackDamage);
}
}
void OnDrawGizmosSelected()
{
if (attackPoint == null)
return;
Gizmos.DrawWireSphere(attackPoint.position, attackRange);
}
}