• 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
Question by jesusfreakmir123 · Apr 24, 2018 at 08:46 PM · healthbarhealth

How to get healthbar to increase and decrease with player health?

I'm working with a team to create a rough like game using Unity and C#. My job is to make the health bar for the player. I got the health bar to display, but I can't seem to get it to communicate with my teammates player's health system. Here's my code:

       using UnityEngine;
       using UnityEngine.UI;
     using System.Collections;

   public class MR_Health : MonoBehaviour
   {
  public int startingHealth = 100;                            // The amount of health the player starts the game 
   with.
    public int currentHealth;                                  // The current health the player has.
   public Slider Slider;                                 // Reference to the UI's health bar.
         public Image damageImage;                                   // Reference to an image to flash on the screen 
            on 
       being hurt.
       public AudioClip deathClip;                                 // The audio clip to play when the player dies.
     public float flashSpeed = 5f;                               // The speed the damageImage will fade at.             
    public Color flashColour = new Color(1f, 0f, 0f, 0.1f);     // The colour the damageImage is set to, to 
    flash.
   
 Animator anim;                                              // Reference to the Animator component.
 AudioSource playerAudio;                                    // Reference to the AudioSource component.
 LH_Health playerMovement;                              // Reference to the player's movement.

LH_Health playerShooting; // Reference to the PlayerShooting script.

 LH_Health playerHealth;
   
 bool isDead;                                                // Whether the player is dead.
 bool damaged;                                               // True when the player gets damaged.


 void Awake()
 {
     // Setting up the references.
     
     anim = GetComponent<Animator>();
     playerAudio = GetComponent<AudioSource>();
     playerMovement = GetComponent<LH_Health>();
     playerShooting = GetComponentInChildren<LH_Health>();
     playerHealth = GetComponent<LH_Health>();

     anim = GetComponent<Animator>();
     // Set the initial health of the player.
     currentHealth = startingHealth;
 }


 void Update()
 {
     playerHealth.getHP();
    
     // If the player has just been damaged...
     if (damaged)
     {
         // ... set the colour of the damageImage to the flash colour.
         damageImage.color = flashColour;
     }
     // Otherwise...
     else
     {
         // ... transition the colour back to clear.
       //  damageImage.color = Color.Lerp(damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
     }

     // Reset the damaged flag.
     damaged = false;
 }


 public void TakeDamage(int amount)
 {
     // Set the damaged flag so the screen will flash.
     damaged = true;

     // Reduce the current health by the damage amount.
     currentHealth -= amount;

     // Set the health bar's value to the current health.
     Slider.value = currentHealth;

     // Play the hurt sound effect.
     playerAudio.Play();

     // If the player has lost all it's health and the death flag hasn't been set yet...
     if (currentHealth <= 0 && !isDead)
     {
         // ... it should die.
         Death();
     }
 }


 void Death()
 {
     // Set the death flag so this function won't be called again.
     isDead = true;

     // Turn off any remaining shooting effects.
     //playerShooting.DisableEffects();

     // Tell the animator that the player is dead.
     anim.SetTrigger("Die");

     // Set the audiosource to play the death clip and play it (this will stop the hurt sound from playing).
     playerAudio.clip = deathClip;
     playerAudio.Play();

     // Turn off the movement and shooting scripts.
     playerMovement.enabled = false;
     playerShooting.enabled = false;
 }

}

My teammate's health system function is LH_Health. GetHp is what he uses to calculate the player health. I have my slider set as the Health bar is the inspector, so I'm not sure why it's not working alt text

unity.png (31.9 kB)
Comment

People who like this

0 Show 0
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

3 Replies

· Add your reply
  • Sort: 
avatar image

Answer by Malace · Apr 24, 2018 at 10:05 PM

It really seems odd to split this into multiple scripts. The health system should handle all things health related. Taking damage, death, re-spawn, as well as update the UI to reflect those changes.


So without the code from the LH_Health script I can't tell you everything that might be wrong here. Though I see a few logical problems I can point out that might help.


  1. LH_Health script is not enabled in your inspector screenshot.

  2. You call GetHP() from that script but you aren't really doing anything with it.? Again I'm not sure what this function does exactly.

  3. You are only setting a slider value on damage taken calls. So unless you call take damage you never change the slider. (which i don't see you do anywhere here)

  4. Why have you written a take damage call at all? Again if the health system is already written. You shouldn't even need this code.


In theory to add in health bar updates to a functional health system script. You should just need to update the slider value to the health value of the script provided. That might be what the GetHP() function does. So slider.value = GetHP(); in a update call should sync whenever his health script updates the health value.


To do the flashing you really need to write this in the actual take damage function. Again I can't figure out why this would be separated from the rest of the health system. So likely this is in the other script already. So your function is never called.

Seeing all the references to his script at the top. I'm pretty sure you should just be modifying your own copy of his script. Once you have the added functionality you have been asked to add, submit it back to them. If everything works they will commit the changes. Seems like your just on the wrong idea you need to write your own script to add these functionalities.


Hope this helps somehow. Working within a team can get chaotic at times.

Comment

People who like this

0 Show 2 · 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 jesusfreakmir123 · Apr 24, 2018 at 10:42 PM 0
Share

I know it's weird, but this is the task I was assigned. Here's my teammates code; public class LH_Health : MonoBehaviour { private int mHealthPoints = 100; private int mHealthCoefficient = 100; private int mSecondsCounter = 0; private int mMaxSeconds = 10; LH_Attack mAttack; void Start() { mAttack = this.GetComponent(); } private void changeHealth(int changeAmt) { if(mAttack.mIsInvincible==false) { if ( (changeAmt + mHealthPoints) <= 100) /checks to make sure hp stays under 100 / { mHealthPoints += changeAmt; } else if ( (changeAmt + mHealthPoints) >= 100) { mHealthPoints = 100; }

         if(mHealthPoints < 0)
         {
             Debug.Log("LH_Health: Player died.");
             mHealthPoints = 100;
         }
     }
     Debug.Log("LH_Health: HP changed to: " + mHealthPoints);

 }
 public void doDamage(uint dmgAmt)
 /*must call with a positive amount for damage */
 {
     int a = Convert.ToInt32(dmgAmt);
     //play sound
     changeHealth( (-a*mHealthCoefficient)/100 );
 }
 public void Heal(int healAmt)
 {
     changeHealth( (healAmt*mHealthCoefficient)/100 );
     //play sound
 }
 public void changeArmor(int percent)  
 {
     mHealthCoefficient = (mHealthCoefficient * percent)/100;
     mSecondsCounter = 0; 
 }
 public void makeInvincible(int seconds)
 {
     mAttack.setInvincible(seconds);
 }
 public int getHP()
 {
     return mHealthPoints;
 }
 // Use this for initialization
 
 // Update is called once per frame
 void Update () {
     
 }

} I updated my code and removed anything that didn't have to do with the health bar. Calling getHp in update just gave me the error of "the name get Hp does not exit in the current context". Here's my updated code: using UnityEngine; using UnityEngine.UI; using System.Collections;

public class MR_Health : MonoBehaviour { public int startingHealth = 100; // The amount of health the player starts the game with. public int currentHealth; // The current health the player has. public Slider slider; // Reference to the UI's health bar. int playerHealth; public int MaxHealth = 100; bool isDead; // Whether the player is dead. bool damaged; // True when the player gets damaged.

 void Awake()
 {

 
    // Set the initial health of the player.
     currentHealth = startingHealth;
 }


 void Update()
 {
     GetComponent<LH_Health>();
   
     slider.value = getHP();
     PositionHealthBar();
     
   // Reset the damaged flag.
     damaged = false;
 }

 public void ChangeHealth(int amount) 
 {
     currentHealth += amount;
     slider.value = currentHealth / MaxHealth;
 }
 private void PositionHealthBar()
 {
     Vector3 currentpos = transform.position;
      
 }
   

}

avatar image Malace jesusfreakmir123 · Apr 25, 2018 at 07:52 AM 0
Share

Okay. So if you need to break it into its own script here is a gist of what you will need to do.


You should only need two reference variables in your script. Maybe more for flashing later. The first should be a reference to the LH_Heath script. Which is easy as it looks to be on the same object. The second is a reference to your slider ui component.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class Display_Health : MonoBehaviour {
     public Slider healthSlider;
     private LH_Health healthscript;
     // Use this for initialization
     void Start () {
         healthscript = this.gameObject.GetComponent<LH_Health>();
         //Assign your slider to the public variable in the inspector.
     }
     
     // Update is called once per frame
     void Update () {
         //here you have to point to the reference of his script and call the gethp function. Which returns an int variable type. 
         //Slider values are 0 through 1 I belive. So you may have to divide by 100 to get the percentage form. IE: 50/100 = .5
         //Sliders also have a On Value Changed function which can call a function any time the slider value gets updated.
         healthSlider.value = healthscript.GetHP()/100;
     }
 
     void SliderChangedFunctionName()
     {
         //Select this script and function name to execute any time the slider changes. This is done in the inspector for the slider.
         // At this point you can just check the reference to the healthscript.GetHP() 
         if (healthscript.GetHP() < 50)
         {
             //start flashing code;
                 } else {
             //stop flashing code;
         }
     }
 }


avatar image

Answer by auzzymo · Apr 24, 2018 at 11:39 PM

You have ... public Slider Slider;

As opposed to naming the variable you've declared it twice? Very new coder here so I could be talking out my a#%

Comment

People who like this

0 Show 0 · 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

Answer by manal1122 · Mar 24, 2019 at 05:08 AM

i want to now how i can make the slider move if the player hits spike or sow

Comment

People who like this

0 Show 0 · 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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

83 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

Related Questions

RTS health bars 2 Answers

Problem with health bar 1 Answer

Destroy Player when Cur_Health <=0 1 Answer

Player health dropping far to fast 1 Answer

Health subtracts when hit by bullit 2 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