Break Coroutine if Collided (Stop Power Up Effect if enters Kill Zone)

Hello I’m trying to figure out a way to lose the power up effects if I enter the kill zone.

For example if I collide with the kill zone while having the power up effect I want the “_jumpForce” to go back its default value of 10f, and destroy the game object.

In this case the power up gives me +10f of “_jumpForce” for 2f seconds then it loses the 10f.

The Kill Zone just Transforms the position of the player.

Also consider I have multiple Power Ups on the map.

My Power Up Scrip:

private void OnTriggerEnter(Collider other)
{
    PlayerController player = other.GetComponent<PlayerController>();
    if (player != null)
    {
        StartCoroutine(PickupJump(player));
    }
}

IEnumerator PickupJump(PlayerController player)
{
    //Instantiate(pickupEffect, transform.position, transform.rotation);

    GetComponent<MeshRenderer>().enabled = false;
    GetComponent<Collider>().enabled = false;
    GetComponentInChildren<Canvas>().enabled = false;

    player.SetJumpForce(_poweredUpIncreaseAmount);

    yield return new WaitForSeconds(_jumpDuration);

    player.SetJumpForce(-_poweredUpIncreaseAmount);

    Destroy(gameObject);

}

Part of Player Controller Script:

public void SetJumpForce(float newSpeedAdjustment)
{
    _jumpForce += newSpeedAdjustment;
}

public void RespawnPlayer() ///////////////
{
    // Get the last correct checkpoint position for this player
    Vector3 respawnPosition = checkpoints.GetPlayerCheckpointPosition(playerTransform);

    if (respawnPosition == Vector3.zero)
    {
        playerTransform.position = startingPosition;
    }
    else
    {
        // Otherwise, respawn the player at the last correct checkpoint position
        playerTransform.position = respawnPosition;
    }
}

Kill zone script:

void OnTriggerEnter(Collider col)
{
    if (col.gameObject.tag == "Player")
    {
        col.gameObject.GetComponent<PlayerController>().RespawnPlayer();
    }
}

Coroutines are great but they’re almost never a good idea if you’re planning on stopping them.

Instead, set a timer that is how long you want the effect to be happening.

private float powerupTimer;

When you award it, set the timer:

powerupTimer = 15; // seconds

Count the timer down normally in an Update():

if (powerupTimer > 0) powerupTimer -= Time.deltaTime;

To see if the powerup is active:

private bool isPowerupActive => powerupTimer > 0;

When you want to stop the effect, set the timer to zero.

powerupTimer = 0;
1 Like