Oldest Instantiation Runs First

I’m working on an auto-battle game and am running into an issue that I can’t seem to resolve. Basically, there’s a path that units walk. Player units walk to the right, and AI enemy units walk to the left until they run into each other. Once they detect an opposing unit, they fight and deal damage to it until one dies, then it continues walking. The play manually spawns their units, while the AI spawns their units on a set timer.

The issue that I’m encountering is that when units fight each other, the unit that was instantiated first always deals damage first and I’m not sure how to remedy this. Even if the units share the same exact attack speed value, the one instantiated first will deal damage first. This is the bit of code I’m running into an issue with:

    private void HandleDetection()
    {
        RaycastHit hit;
        Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 2f, Color.yellow);

        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, 2f, opposingLayerMask))
        {
            Health enemyHealth = hit.transform.gameObject.GetComponent<Health>();
            if (enemyHealth.GetHealth() <= 0)
            {
                return;
            }
            isMoving = false;
            animator.SetBool("isWalking", false);
            animator.SetBool("isPunching_Left", true);
            aiCombat.EnterCombat(enemyHealth);
        }
    }
    void Update()
    {
        if (unitHealth.GetHealth() <= 0)
        {
            return;
        }
        if (inCombat)
        {
            if (enemy == null)
            {
                inCombat = false;
                //Debug.Log("Leaving combat");
                nav.ResumeMovement();
            }
            if (enemy.GetHealth() <= 0)
            {
                inCombat = false;
                //Debug.Log("Leaving combat");
                nav.ResumeMovement();
            }
            timer += Time.deltaTime;
            if (timer >= attackSpeed)
            {
                enemy.TakeDamage(attackPower);
                Debug.Log(this + "Attacking" + enemy);
                timer = 0;
            }
        }
    }

Both units successfully detect each other and play the punching animation from the first block, but then when it comes to taking damage, the unit instantiated first deals damage first. For testing, I have all units at 1 HP and they deal 1 damage, so the first hit is an instant kill.

Is there something that I’m missing here? I was thinking that maybe I should implement logic that would prevent a unit from dying until they complete their attack?

That’s actually a thing. Often times all damage is dealt, then all deaths are checked at the same time.

2 Likes