简体   繁体   中英

How do i create auto hp regeneration script after taking dmg?

I am currently trying to script an auto hp regenerate script, similar to games like halo where you regain health after some time of not taking dmg. It almost works, right now it auto regenerates hp 5 seconds after taking dmg, however if i take dmg during those 5 seconds it still keeps regenerating.

I have created a static boolean in the player script called canRegenerate = true; This boolean turns false when player takes dmg. The rest is in the script below, it turns the boolean to true again after 5 seconds.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.Analytics;

public class HealthBarScript : MonoBehaviour {


    Image FullHearts;
    public float maxHealth = 100f;
    public static float health;
    public bool canRegen = false;


    // Use this for initialization
    void Start ()
    {
        FullHearts = GetComponent<Image>();
        health = maxHealth;
    }

    // Update is called once per frame
    void Update ()
    {
        FullHearts.fillAmount = health/maxHealth;
    }


    void FixedUpdate ()
    {
        if (Player1.canRegenerate == true && health < 100f)
        {
                health = health + 0.5f;
        }


        if (Player1.canRegenerate == false)
        {
            StartCoroutine(Regenerate());
        }
    }

    IEnumerator Regenerate()
    {
        yield return new WaitForSeconds(5);
            Player1.canRegenerate = true;


    }

}

Right now, you are possibly starting multiple coroutines that will wait 5 seconds and then set canRegenerate to true. Multiple coroutine calls will make it look like the player will always regenerate, given the correct timing.

You need to gate the coroutine from being called more than once.

private bool CRRegenerateIsRunning = false;

void FixedUpdate ()
{
    if (Player1.canRegenerate && health < 100f)
    {
        health += 0.5f;
    }

    if (!Player1.canRegenerate && !CRRegenerateIsRunning)
    {
        StartCoroutine(Regenerate());
    }
}

IEnumerator Regenerate()
{
    CRRegenerateIsRunning = true;
    yield return new WaitForSeconds(5);

    Player1.canRegenerate = true;
    CRRegenerateIsRunning = false;
}

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