1

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 + "%";
    }
}
user58519
  • 579
  • 1
  • 4
  • 19
  • `Update` is executed once per frame, so every frame of the game you are increasing the player's health. You obviously need to add some conditions when this should be happeneing – UnholySheep Dec 20 '20 at 16:09

1 Answers1

3

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 + "%";
        }
    }
}
jjxtra
  • 20,415
  • 16
  • 100
  • 140