简体   繁体   中英

Unity heal over time

I just implemented a heal overtime to my unity project and I was wondering how do I stop the heal overtime while the player in in range of the enemy.. and then start the heal overtime when the player is out of range of the enemy? I tried using a bool and it didn't work.. I also tried using StopCoroutine what also didn't work

Here is my code:

private void Awake()
{
    if (currentHealth < 100)
    {
        StartCoroutine(HealCo());
    }
 
    healDuration = new WaitForSeconds(2f);
}

private void Update()
{
    healthbar.value = currentHealth;
   
    if (currentHealth > maxHealth)
    {
        currentHealth = 100;
    }
}    

private IEnumerator HealCo()
{
    currentHealth += healAmount;
    yield return healDuration;
    StartCoroutine(HealCo());
}
public void TakeDamage(int damage)
{
    Save();
    damagePosition.position = playerPosition.position;

    if (damaged == true)
    {
        HurtSFX();
        isDamaged = true;
        StartCoroutine(FlashCo());
        CameraShake.ShakeOnce();
        
        if (isDamaged)
        {
            StartCoroutine(DamagedCo());
        }

        ShowDamage(damage.ToString());
        currentHealth -= damage;
        healthbar.value = currentHealth;

        if (currentHealth < 4)
        {
            cameraFollow.enabled = false;
            playerMovement.enabled = false;
            StartCoroutine(PlayerDeathCo());
            CoinManager.Instance.DecreaseValue(1);
            playerPosition.position = deathPosition.position;
            graveStonePosition.position = damagePosition.position;
            graveStone.SetActive(true);
        }
    }

One option would be to use theenabled flag that all MonoBehaviours already have.

private void OnEnable()
{
    StartCoroutine(HealingLoop());
}

public void SetHealth(float value)
{
    currentHealth = Mathf.Clamp(value, 0f, 100f);
    healthbar.value = currentHealth;
}

private IEnumerator HealingLoop()
{
    while(enabled)
    {
        yield return healDuration;
        SetHealth(currentHealth + healAmount)
    }
}

This relies on HealingLoop coming to an end when the enabled flag is set to false, and the OnEnable event function starting it running again when the flag is set back to enabled.

You don't need a coroutine if you are using Update() method. It really depends on the architecture and what you exactly need, but the easiest way for me will be to create the method Heal() and check in Update() if it should be invoked. That can be done using bool isHealing which value can be set whatever you want.

If you want to heal exact value of HP or time then calculate everything in update like (timeHealing - Time.deltaTime) etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM