L
L
LeBrone2021-12-02 14:05:51
C++ / C#
LeBrone, 2021-12-02 14:05:51

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);
        }
    }


Damage script:
public void TakeDamage(int damage)
    {
        currentHealth -= damage;

        if (currentHealth <= 0)
        {
            Die();
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ente, 2021-12-02
@LeBrone

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);
}

In this script, it will be possible to change health through the Change function, and in any direction, both damage and healing can take place, it all depends on the sign in the transferred amount variable. Also the script throws an event that the health has changed so that other scripts can subscribe and respond. For example, a script that draws a health bar or a script that is responsible for character death.
The second script is Damage.cs. It will work on triggers in Unity, and when objects intersect with each other, the damage function will be called, for example, if a character stands in a fire, he will be affected by a bullet or a sword. Of course, you need to give them triggers of the right size, both to the object with damage and to the one who is being damaged + set the collision matrix correctly so that OnTriggerEnter2D does not affect other objects that are not its target.
[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 question

Ask a Question

731 491 924 answers to any question