How to Sync Animation with Code

I’m trying to set up Melee combat in my 2D Platformer. The issue I’ve run into is that the animation and actual damage effect in the code are out of sync. For example the enemy gets knocked back when hit by the player, but this happens before the character’s fist is even close to the enemy. My solution was to have a variable decrease by Time.deltaTime. When the variable reaches a certain value, the damage happens. For whatever reason, this hasn’t work. Here’s what I’m working with.

public class PlayerAttack : MonoBehaviour
{
    [SerializeField]float timeBtwAttack;
    public float startTimeBtwAttack;

    public float attackRangeX;
    public float attackRangeY;
    public Transform attackPos;
    public int damage;

    public LayerMask whatIsEnemy;
    public LayerMask whatIsDestructable;

    private Animator anim;

    void Start()
    {
        anim = this.GetComponent<Animator>();
    }

    void Update()
    {
        if(timeBtwAttack <= 0)
        {
            if (Input.GetKeyDown(KeyCode.Return))
            {
                Punch();
            }
        }
        else
        {
            timeBtwAttack -= Time.deltaTime;
        }
    }

    void Punch()
    {
        anim.SetTrigger("attack");

        if(timeBtwAttack <= 0.015)
        {
            Collider2D[] enemiesToDamage = Physics2D.OverlapBoxAll(attackPos.position, new Vector2(attackRangeX, attackRangeY), 0, whatIsEnemy);
            for (int i = 0; i < enemiesToDamage.Length; i++)
            {
                enemiesToDamage*.GetComponent<enemyController>().TakeDamage(damage);*

}

Collider2D[] destructablesToDamage = Physics2D.OverlapBoxAll(attackPos.position, new Vector2(attackRangeX, attackRangeY), 0, whatIsDestructable);
for (int i = 0; i < destructablesToDamage.Length; i++)
{
destructablesToDamage*.GetComponent().TakeDamage(damage);*
}
}

timeBtwAttack = startTimeBtwAttack;
}
When the player hits the Return key, timeBtwAttack begins to decrease. When this variable is at 0, they player can attack again. I took this variable and put its value as a condition to trigger the damage code. For whatever reason, regardless of the variable’s value, damage is still dealt.

Hey,

A system to time animation and code, that is easier to implement, is by using Animation Events.
Whenever a certain point in your animation is reached, you can set an event so that your code gets fired.