0
\$\begingroup\$

What I did here works, but it looks messy and funny to me.

void Update()
{
    rb = GetComponent<Rigidbody2D>();

    if(BossHP <= 2)
    {
        PhaseTwo.Invoke();
    }
}

private void OnTriggerEnter2D(Collider2D collision)
{
    if(collision.gameObject.CompareTag("Circle"))
    {
        BossHP--;
        Debug.Log(BossHP);
    }
}

When I put if(BossHP <= 2) { PhaseTwo.Invoke(); } under void OnTriggerEnter2D, it only spawns once. So that's why I put under Update. But ...is this the right way? It looks funny to me.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

The reason it's only invoking PhaseTwo once is likely because the circle continues overlapping this script's object. OnTriggerEnter2D won't get called again for this pair of colliders until the colliders separate and then overlap again.

If you want to continuously invoke this event every frame after reaching this threshold health, an alternative would be to start a coroutine:

const int LOW_HEALTH_THRESHOLD = 2;
Coroutine _lowHealthLoop;

private IEnumerator LowHealth() {
    while (BossHP < LOW_HEALTH_THRESHOLD) {
        PhaseTwo.Invoke();
        yield return null;
    }
    _lowHealthLoop = null;
}

private void OnTriggerEnter2D(Collider2D collision)
{
    if(collision.gameObject.CompareTag("Circle"))
    {
        BossHP--;
        Debug.Log(BossHP);

        if (BossHP < LOW_HEALTH_THRESHOLD && _lowHealthLoop == null) {
            _lowHealthLoop = StartCoroutine(LowHealth());
        }
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .