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 primus88 · May 18, 2013 at 07:29 PM · guihealthbar

Adding a floating health bar

Hello guys,

I need a simple health bar to add it on top of each of my spawned soldiers in a strategy game. Further down I will copy my script that takes care of health:

 using UnityEngine;
 using System.Collections;
 
 
 public class health : MonoBehaviour {
     //max health. you set this to what you want his health to be
     public int maxhealth=50;
     public int currenthealth;
     //cant die
     public bool invincible;
     public bool dead;
     
     
         
     // Use this for initialization
     void Start () {
         givereward=true;
         
         AI ai=(AI)GetComponent("AI");
         if(ai) ai.health=maxhealth;
         
     currenthealth=maxhealth;
     healthsave=maxhealth;
         
     }
     
     // Update is called once per frame
     void Update () {
     
         
         
         //tell ai when health is changed
         if(healthsave>currenthealth|healthsave<currenthealth){
             AI ai=(AI)GetComponent("AI");
             if(ai){
             ai.health=currenthealth;
             healthsave=currenthealth;
                 
             }
         }
         
         //death 
         if(dead){
             AI ai=(AI)GetComponent("AI");
                 if (ai && !ai.dead){ // if ai.dead not set yet...
     ai.dead = true; // set it and destroy capsule
     Destroy(transform.Find("Capsule").gameObject);
     }
             //tell ai that he is dead
             if(ai)ai.dead=true;        
             Destroy (gameObject,30);
             
         }
         else {
             givereward=true;
         }
         
         if(currenthealth>=maxhealth) currenthealth=maxhealth;
         
         //if health is less than zero
         if(currenthealth<=0){
             //check if invincible if not death
             if(invincible)dead=false;
             else dead=true;
             currenthealth=0;
         }
         //regenerate
         if(regenerate){
             if(currenthealth<maxhealth&currenthealth>0){
         regtimer+=Time.deltaTime;
         if(regtimer>regenerationtime){
                     currenthealth=currenthealth+regenerationamount;
                     regtimer=0;
                 }
         
         }
         }
     }
     
 
 }

What is needed to add to the code to have a simple health bar ? I tried and created one with GUIText, and eve though it was visible on the camera, it didn't show when I attached it with the script to an object.

Please help :D

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

2 Replies

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

Answer by MikeNewall · May 19, 2013 at 02:13 AM

Here you go! All you need to do is hook up your health variable.

 using UnityEngine;
 
     public class HealthBar : MonoBehaviour 
     {
         public Font font;
         public int fontSize = 8;
         public Vector3 Offset = Vector3.zero; // The offset from the character
         
         private float health = 100;
         
         private TextMesh bar;
         
         void Start()
         {
             // Setup the text mesh
             bar = new GameObject("HealthBar").AddComponent("TextMesh") as TextMesh;
             bar.gameObject.AddComponent("MeshRenderer");
             bar.gameObject.transform.parent = transform;
             bar.transform.localPosition = Vector3.zero + Offset;
             
             if(font) bar.font = font;
             else bar.font = GUI.skin.font;
             bar.renderer.material = font.material;
             bar.characterSize = 0.25f;
             bar.alignment = TextAlignment.Center;
             bar.anchor = TextAnchor.MiddleCenter;
             bar.fontSize = fontSize;
         }
         
         void Update()
         {
             // Hook up your health variable here
             if(bar.text != "HP: " + health.ToString()) bar.text = "HP: " + health.ToString();
         }
     }
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 primus88 · May 19, 2013 at 09:10 AM 0
Share

Thanks, but I don't understand exactly what you mean by health variable. Which block of script are you refering to as health variable ?

avatar image MikeNewall · May 19, 2013 at 11:16 AM 0
Share

The text that displays the health is being set in Update using the health variable. When that variable changes the text updates with it.

You need to change the update code to use the variable which stores the health of your soldier.

 if(bar.text != "HP: " + health.ToString()) bar.text = "HP: " + health.ToString();

All that line says is if the health bar text is different from our current health then update the text. "health" is what you need to replace with the variable that stores your soldiers health

avatar image primus88 · May 19, 2013 at 11:35 AM 0
Share

Yes, I tried replace the health.ToString() into currenthealth.ToString() also declaring in the HealthBar script the health script :

public class health = health;

Still not working

Basicly I don't know how to address the variable currenthealth from the health.cs in the HealthBar.cs script. Any ideas ?

avatar image MikeNewall · May 19, 2013 at 11:54 AM 0
Share

You need to get a reference to your health script. As long as the health bar script is attached to your soldier you can use GetComponent do do that.

 public class HealthBar : $$anonymous$$onoBehaviour 
 {
     private Health health;
 
     void Start()
     {
          health = GetCompnent("Health") as Health;
     }
 }

Then you can go:

 health.currentHealth

to access your health.

avatar image primus88 · May 19, 2013 at 12:01 PM 0
Share

private Health .. it says I should have it as something else.. Float or .. ?

And for health = GetCompnent("Health") as Health; it says : HealthBar.Health is a 'field' but a 'type' was expected

Show more comments
avatar image
0

Answer by primus88 · May 19, 2013 at 03:31 PM

All I need is a script in C# that creates a healthbar (green front and grey Background), that decreases when health of object goes down.

I tried so many things for days now that is getting very frustrating considering I solved much more complicated things than this..

Any help would be gretely appreciated.

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

15 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

Related Questions

Why the healtbar is moving ? 0 Answers

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Setting Scroll View Width GUILayout 1 Answer

GUI healthbar 3 Answers

how to "blink" more often? 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