Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by Spiritzz · Jun 21, 2019 at 06:22 PM · coroutinesregenerationhealth

Health Regen After X seconds

Trying to get health to regen after being hit. I've tried a few different ways but this is where I get stuck: each time I add functionality for a wait time between getting hit and regaining health. I got it to work at a stage, but then when the player takes, say, 1 damage and a second later 2 damage, it will run either two coroutines in parallel, or just regen health after it took the first amount of damage (1 in this case).

Please help! :P

public class NewPlayerStats : MonoBehaviour {

 public int startingHealth = 5;
 public int currentHealth;
 public int healthReg = 1;

 bool isRegenHealth;


 void Awake()
 {
     currentHealth = startingHealth;
 }


 void Update()
 {
     if (currentHealth != startingHealth && !isRegenHealth)
     {
         StartCoroutine(RegainHealthOverTime());
     }
 }


 private IEnumerator RegainHealthOverTime()
 {
     isRegenHealth = true;
     while (currentHealth < startingHealth)
     {
         Healthregen();
         yield return new WaitForSeconds(1);
     }
     isRegenHealth = false;
 }


 public void Healthregen()
 {
     currentHealth += healthReg;

 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Hellium · Jun 21, 2019 at 08:31 PM

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class NewPlayerStats : MonoBehaviour
 {
     [SerializeField]
     private int maxHealth = 5;
 
     [SerializeField]
     private float healthRegenerationRate = 1;
 
     [SerializeField]
     private float regenerationDelay = 1;
 
     private int currentHealth;
 
     private float lastDamagesTime = -1;
 
     private float regeneratedHealth;
 
     public bool IsDead
     {
         get { return currentHealth == 0; }
     }
 
     private void Awake()
     {
         currentHealth = maxHealth;
     }
 
     void Update()
     {
         if ( lastDamagesTime >= 0 && Time.time - lastDamagesTime >= regenerationDelay )
         {
             RegenerateHealth();
         }
     }
 
     public void RegenerateHealth()
     {
         regeneratedHealth += healthRegenerationRate * Time.deltaTime;
         int flooredRegeneratedHealth = Mathf.FloorToInt( regeneratedHealth );
         regeneratedHealth -= flooredRegeneratedHealth;
         Heal( flooredRegeneratedHealth );
     }
 
     public void Hurt( int damages )
     {
         if ( damages < 0 )
             throw new System.ArgumentException( "Damages must be greater or equal to 0", nameof( damages ) );
 
         if ( IsDead )
             return;
 
         currentHealth = Mathf.Clamp( currentHealth - damages, 0, maxHealth );
         regeneratedHealth = 0;
         lastDamagesTime = Time.time;
 
         if( IsDead )
         {
             // Die
         }
     }
 
     public void Heal( int amount )
     {
         if ( amount < 0 )
             throw new System.ArgumentException( "Healed amount must be greater or equal to 0", nameof( amount ) );
 
         currentHealth = Mathf.Clamp( currentHealth + amount, 0, maxHealth );
         if( currentHealth == maxHealth )
         {
             lastDamagesTime = -1;
             regeneratedHealth = 0;
             // Full health
         }
     }
 }
Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Spiritzz · Jun 22, 2019 at 09:19 AM 0
Share

Thanks! Although I think there's something wrong in the update method and it's blowing my $$anonymous$$d to be honest.

The player never regains health after taking damage. I tested by creating a start function that uses Damage(2); to instantly hurt the player. He takes the damage but the health never goes up.

avatar image Hellium Spiritzz · Jun 22, 2019 at 09:21 AM 0
Share

Everything works perfectly fine here. The value of regenerationDelay represents the number of seconds before the health starts to regenerate. Are you sure its value is not too big?


Are you sure the script is enabled? The checkbox in the top-left corner of the script must be checked. Otherwise the Update won't run. And make sure the gameObject is active.

avatar image Spiritzz Hellium · Jun 22, 2019 at 09:28 AM 0
Share

I made regenerationDelay 1 for testing. Perhaps because I'm instantly applying damage to the player it isnt considering it? I can try using a different way to apply damage and test that. Right now there are no enemies in the game so i'll still need to simulate it some other way

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

179 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

If statements inside coroutine aren't running 2 Answers

Stopping the player from regenerating health when it takes damage 0 Answers

Health Regeneration through Photon RPC 1 Answer

Help me with health script 2 Answers

Unity crashes ONLY when this function gets called many times per second. Help would be very appreciated. 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges