Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
avatar image
0
Question by Yourname · Apr 18, 2015 at 10:46 PM · healthbarnegativehealth

HealthBar goes negative?

Does anyone know how to make the healthbar stop at zero? (it currently goes below zero) Thank you.

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class HealthBar : MonoBehaviour
 {
     #region FIELDS
     
     // The player's current health
     public int currentHealth;
     
     // The player's max health
     public int maxHealth;
     
     // The health bar's speed
     public float healthSpeed;
     
     // The health text
     public Text healthText;
     
     // The health's image, this is used for color changing
     public Image visualHealth;
     
     // The current xValue of the health
     private float currentValue;
     
     // How often can I take damage
     public float cooldown;
     
     // Indicates if we can take damage or not
     private bool onCD;
     
     // The healthbar's canvas
     public Canvas canvas;
     
     #endregion
     
     #region PROPERTIES
     
     // Property for accessing the player's health
     public int Health
     {
         get
         { 
             return currentHealth;
         }
         set
         {
             currentHealth = value;
         }
     }        
     
     #endregion
     
     // Use this for initialization
     void Start()
     {
         // Sets all start values
         onCD = false;
         
         //Sets the current health to the maxHealth
             currentHealth = maxHealth;    
     }
     
     // Update is called once per frame
     void Update()
     {
         HandleHealthbar();
         if (Input.GetKeyDown(KeyCode.Space))
         {
             Health -= 10;
         }
     }
     
     // Handles the healthbar my moving it and changing color
     private void HandleHealthbar()
     {
         // Writes the current health in the text field
         healthText.text = "Health: " + currentHealth;
         
         // Maps the min and max position to the range between 0 and max health
         currentValue = Map( currentHealth, 0, maxHealth, 0, 1);
         
         // Sets the fillAmount of the health to simulate reduction of health 
         visualHealth.fillAmount = Mathf.Lerp( visualHealth.fillAmount, currentValue, Time.deltaTime * healthSpeed );
         
         // If we have more than 50% health we use the green colors
         if ( currentHealth > maxHealth /2 )
         {
             visualHealth.color = new Color32( ( byte ) Map( currentHealth, maxHealth / 2, maxHealth, 255, 0 ), 255, 0, 255 );
         }
         // If we have less than 50% health we use the red colors
         else 
         {
             visualHealth.color = new Color32( 255, ( byte ) Map ( currentHealth, 0, maxHealth / 2, 0, 255 ), 0, 255); 
         }
     }
     
     void OnTriggerStay( Collider other )
     {
         // Used for simulating taking damage
         if ( other.tag == "Damage" )
         {
             if ( !onCD && currentHealth > 1 )
             {
                 // Makes sure that we can't take damage right away
                 StartCoroutine ( CoolDownDmg() );
                 // Uses the Health Property so that we recolor and rescale the health when we change it
                 Health -= 1;
             }
         }
         
         // Used for simulating gaining health
         if ( other.tag == "Health" )
         {
             if ( !onCD && currentHealth < maxHealth )
             {
                 // Makes sure that we can't take damage right away
                 StartCoroutine( CoolDownDmg() );
                 // Uses the Health Property so that we can recolor and rescale the health when we change it
                 Health += 1;
             }
         }
     }
     
     // Keeps track of the damage CD
     IEnumerator CoolDownDmg()
     {
         onCD = true;
         // Waits a while before we are able to take damage again
         yield return new WaitForSeconds( cooldown );
         onCD = false;
     }
     
     // This method maps a range of numbers into another range
     // <param name="x">The value to evaluate</param>
     // <param name="in_min">The minimum value of the evaluated variable</param>
     // <param name="in_max">The maximum value of the evaluated variable</param>
     // <param name="out_min">The minimum number we want to map to</param>
     // <param name="out_max">The maximum number we want to map to</param>
     // <returns></returns>
     public float Map(float x, float in_min, float in_max, float out_min, float out_max)
     {
         return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
     }
     
     
 }
 ![alt text][1]


[1]: /storage/temp/44731-heaalq.jpg

heaalq.jpg (185.6 kB)
Comment
Add comment · Show 2
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 Yourname · Apr 18, 2015 at 07:00 PM 0
Share

I added:

  if (Health <= 0)
         {
             Health = 0;
         }

The health now stops going negative, but there is still one issue:

once the currentHealth = 0, the fill keeps cycling (is there a way to stop the fill from continuously going down?)

I tried this:

 // Sets the fillAmount of the health to simulate reduction of health 
 if currentHealth !=0 ()
 {
 visualHealth.fillAmount = $$anonymous$$athf.Lerp( visualHealth.fillAmount, currentValue, Time.deltaTime * healthSpeed );
 }

The issue is once current health = 0 the fill amount stops in its tracks (ie. does not reach 0 fill since it is going down over time) Anyone know how to fix this?

alt text

avatar image siaran · Apr 20, 2015 at 03:28 PM 0
Share

why don't you check if the fillAmount is 0 ins$$anonymous$$d of currentHealth there? Then it should keep lerping until it's at 0, and not do it when it is.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by habsi70 · Apr 20, 2015 at 05:28 PM

You can limit the value of Health when setting it, the code could be written more compact:

 public int Health
      {
          get
          { 
              return currentHealth;
          }
          set
          {
              if (value >= 0) {
                  currentHealth = value;
              }
              else {
                  currentHealth = 0;
              }
          }
      } 

Comment
Add comment · 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

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Health Bar going 0 right away 1 Answer

Regain health on GUI 2 Answers

Pause Script 1 Answer

Issue with GUITexture width. 1 Answer

Health Bar Division like in MOBA 1 Answer


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