Answer the question
In order to leave comments, you need to log in
How to make Player deal damage to Enemy?
I am newbie. Wrote a script to make the Player attack Enemy, but the damage does not pass through Enemy. Help me please.
Attack script:
void Attack()
{
anim.SetTrigger("Attack");
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
if (collision.tag == "Enemy")
{
collision.GetComponent<Health>().TakeDamage(damage);
}
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
if (currentHealth <= 0)
{
Die();
}
}
Answer the question
In order to leave comments, you need to log in
Make yourself two scripts, the first one will be for all objects in the game that have health, these can be characters (your player, enemies), objects (doors, walls, etc.)
These objects will have a script, let's call it Health.cs
[SerializedField] private int hitpoints = 100;
public Action<int, int> OnChange;
public void Change(int amount)
{
hitpoints += amount;
OnChange?.Invoke(hitpoints, amount);
}
[SerializedField] private int amount = -10;
public Action<int> OnDamage;
private void OnTriggerEnter2D(Collider2D collider)
{
collider.gameObject.GetComponent<Health>().Change(amount);
OnDamage?.Invoke(amount);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question