Search code examples
c#unity-game-enginedelay

How to delay add more health to player in Unity C#?


C# Unity3D when the player was attack I want to slow add player health until 100%. I try to add more health with this code by using PlayerHealth++ but it's very fast to add health that make player never die. How to fix it?

public class HealthScript : MonoBehaviour
{

    [SerializeField] Text HealthText;

    void Start()
    {
        HealthText.text = SaveScript.PlayerHealth + "%";

    }

    void Update()
    {
        SaveScript.PlayerHealth++;
        HealthText.text = SaveScript.PlayerHealth + "%";
    }
}

Solution

  • Easy way is put a interval param on that script - a float which can be the seconds that need to expire before health is added.

    Keep a second variable which is a time accumulater. Every update method add Time.deltaTime to this accumulator variable.

    Finally, if this accumulator is greater than the interval, increment the players health and reset the accumulator to 0.

    public class HealthScript : MonoBehaviour
    {
        [Tooltip("How long in seconds before health is incremented")]
        public float HealthInterval = 5.0f;
        
        private float healthIntervalAccumulator;
        
        [SerializeField] Text HealthText;
    
        void Start()
        {
            HealthText.text = SaveScript.PlayerHealth + "%";
    
        }
    
        void Update()
        {
            if ((healthIntervalAccumulator += Time.deltaTime) >= HealthInterval)
            {
                healthIntervalAccumulator = 0.0f;
                SaveScript.PlayerHealth++;
                HealthText.text = SaveScript.PlayerHealth + "%";
            }
        }
    }