• 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
1
Question by ahmedelmasry0123 · Feb 04, 2018 at 06:28 AM · healthbar

how can i make the division of the health bar like a lol health bar ?

i want know how to make the division like this picture alt text

& another thing how to make that effect of damage on health bar like this ?alt text

3zl6hhs.jpg (131.3 kB)
untitled-2.jpg (84.3 kB)
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
4
Best Answer

Answer by Hellium · Feb 04, 2018 at 09:34 AM

Here is a little shader I made for you:

  1. Create a new shader and name it "HealthBar"

  2. Open it using MonoDevelop / Visual Studio and copy-paste the code

  3. In Unity, create a new material and select the "Sprites/HealthBar" shader

  4. Create a new UI Image in your scene, and apply the material you have created step 3.

  5. You can put an image in the Image component, but the image type must be set to "Simple", and "Preserve aspect" must be unchecked


Here is an example image I've used:

Healthbar


Thanks to the shader, you will be able to:

  1. Set the main color of the bar if you have an enemy / friend

  2. Indicate the number of "steps" (black bars). If the character has 100 max HP and each little square represents 25HP, then, steps must be equals to 100/25 = 4

  3. Indicate the remaining life (using percentage)

  4. Define the color of the bar when your character takes damages using the inspector

  5. Indicate the damages taken by the character (using percentage)

  6. Define the color of the border using the inspector

  7. Define the width of the border using the inspector

    Result

Result

Shader code


  Shader "Sprites/HealthBar"
  {
      Properties
      {
         [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
          [Header(Life)]_Color ("Main Color", Color) = (0.2,1,0.2,1)
          _Steps ("Steps", Float) = 1
          _Percent ("Percent", Float) = 1
      
          [Header(Damages)]_DamagesColor ("Damages color", Color) = (1,1,0,1)
          _DamagesPercent ("Damages Percent", Float) = 0
      
      
          [Header(Border)]_BorderColor ("Border color", Color) = (0.1,0.1,0.1,1)
          _BorderWidth ("Border width", Float) = 1
          [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
      
      
          _ImageSize ("Image Size", Vector) = (100, 100, 0, 0)
      }
  
      SubShader
      {
          Tags
          { 
              "Queue"="Transparent" 
              "IgnoreProjector"="True" 
              "RenderType"="Transparent" 
              "PreviewType"="Plane"
              "CanUseSpriteAtlas"="True"
          }
  
          Cull Off
          Lighting Off
          ZWrite Off
          Blend One OneMinusSrcAlpha
  
          Pass
          {
          CGPROGRAM
              #pragma vertex vert
              #pragma fragment frag
              #pragma multi_compile _ PIXELSNAP_ON
              #include "UnityCG.cginc"
              
              struct appdata_t
              {
                  float4 vertex   : POSITION;
                  float4 color    : COLOR;
                  float2 texcoord : TEXCOORD0;
              };
  
              struct v2f
              {
                  float4 vertex   : SV_POSITION;
                  fixed4 color    : COLOR;
                  half2 texcoord  : TEXCOORD0;
              };
              
              fixed4 _Color;
              half _Steps;
              half _Percent;
              
              fixed4 _DamagesColor;
              half _DamagesPercent;
              
              fixed4 _BorderColor;
              half _BorderWidth;
  
              v2f vert(appdata_t IN)
              {
                  v2f OUT;
                  OUT.vertex = UnityObjectToClipPos(IN.vertex);
                  OUT.texcoord = IN.texcoord;
                  #ifdef PIXELSNAP_ON
                  OUT.vertex = UnityPixelSnap (OUT.vertex);
                  #endif
  
                  return OUT;
              }
  
              sampler2D _MainTex;
              float4 _ImageSize;
  
              fixed4 frag(v2f IN) : SV_Target
              {
                  fixed4 c = tex2D(_MainTex, IN.texcoord);
                  
                  if ( IN.texcoord.x > _Percent + _DamagesPercent )
                  {
                     c.a = 0 ;
                  }
                  else
                  {
                      if ( IN.texcoord.x > _Percent )
                         c *= _DamagesColor ;
                      else
                      {
                         if( (IN.texcoord.x * _ImageSize.x ) % (_ImageSize.x / _Steps) < _BorderWidth )
                             c *= _BorderColor;
                         else if ( IN.texcoord.y * _ImageSize.y < _BorderWidth )
                             c *= _BorderColor;
                         else
                             c *= _Color;
                      }
                  }
                      
                  
                  c.rgb *= c.a;
                  return c;
              }
          ENDCG
          }
      }
  }

C# code

 Here is a C# script to manipulate the HealthBar:
 
 using UnityEngine;
 using UnityEngine.UI;
 
 public class HealthBar : MonoBehaviour
 {
     [SerializeField]
     private Image image ;
     
     [SerializeField]
     private float maxHealthPoints = 100;
     
     [SerializeField]
     private float healthBarStepsLength = 10;
     
     [SerializeField]
     private float damagesDecreaseRate = 10;
     
     private float currentHealthPoints ;
     
     private RectTransform imageRectTransform ;
     
     private float damages;
 
     public float Health
     {
         get { return currentHealthPoints; }
         set
         {
             currentHealthPoints = Mathf.Clamp(value, 0, MaxHealthPoints);
             image.material.SetFloat("_Percent", currentHealthPoints / MaxHealthPoints);
 
             if (currentHealthPoints < Mathf.Epsilon)
                 Damages = 0;
         }
     }
 
     public float Damages
     {
         get { return damages; }
         set
         {
             damages = Mathf.Clamp(value, 0, MaxHealthPoints);
             image.material.SetFloat("_DamagesPercent", damages / MaxHealthPoints);
         }
     }
 
     public float MaxHealthPoints
     {
         get { return maxHealthPoints; }
         set
         {
             maxHealthPoints = value;
             image.material.SetFloat("_Steps", MaxHealthPoints / healthBarStepsLength);
         }
     }
 
     protected void Awake()
     {
         imageRectTransform = image.GetComponent<RectTransform>();
         image.material = Instantiate(image.material); // Clone material
 
         image.material.SetVector( "_ImageSize", new Vector4( imageRectTransform.rect.size.x, imageRectTransform.rect.size.y, 0, 0) );
 
         MaxHealthPoints = MaxHealthPoints; // Force the call to the setter in order to update the material
         currentHealthPoints = MaxHealthPoints; // Force the call to the setter in order to update the material
     }
     
     protected void Update()
     {
         if( Damages > 0 )
         {
             Damages -= damagesDecreaseRate * Time.deltaTime;
         }
         
         // Dummy test, you can remove this
         if( Input.GetKeyDown(KeyCode.Space) )
         {
             Hurt( 20 );
         }
     }
     
     public void Hurt( float damagesPoints )
     {
         Damages = damagesPoints ;
         Health -= Damages;
     }
 }


[3]: /storage/temp/110662-healthbar.png


healthbar.jpg (76.4 kB)
Comment
Add comment · Show 14 · 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 ahmedelmasry0123 · Feb 07, 2018 at 07:11 AM 0
Share

actually i don't know how to do that ?

avatar image Hellium ahmedelmasry0123 · Feb 07, 2018 at 07:14 AM 0
Share

I've described the step at the beginning of my answer ;)

  1. Create a new shader and name it "HealthBar"

  2. Open it using $$anonymous$$onoDevelop / Visual Studio and copy-paste the code

  3. In Unity, create a new material and select the "Sprites/HealthBar" shader

  4. Create a new UI Image in your scene, remove the default sprite, and apply the material you have created step 3

avatar image ahmedelmasry0123 Hellium · Feb 08, 2018 at 02:25 AM 0
Share

Thanks it working very well now :) Where i can add my own texture for it?
alt text

110887-healthbar.png (1.4 kB)
Show more comments
avatar image PersianKiller ahmedelmasry0123 · Feb 07, 2018 at 07:15 AM 0
Share

@ahmedelmasry0123,what does lol health bar mean? if you need a simple healthBar I can show you an ultra easy example.but I don't know what lol heathBar is !!!!

avatar image ahmedelmasry0123 PersianKiller · Feb 08, 2018 at 12:08 AM 0
Share

like league of legends health bar alt text

avatar image fafase · Feb 13, 2018 at 09:55 AM 0
Share

Why not just an image with transparency on top of the health bar?

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

75 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

Related Questions

Splitscreen w/ different GUIs on each camera 2 Answers

Healthbar not always working, someone please help! 2 Answers

GUI.HorizontalScrollbar won't change it's height 1 Answer

GuiTexture above 3D objects 1 Answer

NullReferenceException: Object reference not set to an instance of an object 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