Search Unity

  1. Are you interested in providing feedback directly to Unity teams? Sign up to become a member of Unity Pulse, our new product feedback and research community.
    Dismiss Notice

Health and Progress Bar Pro

Discussion in 'Assets and Asset Store' started by Democide, Mar 30, 2017.

  1. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    This is the thread to put in all information, announcements and questions into one place. This first post will be updated as we go along. Feel free to follow or reach out to me on twitter at @mnerurkar.


    What is Health and Progress Bar Pro?
    If you want a good looking and useful ui bar, whether horizontal, vertical or circular, then you've come to the right place. The Progress Bar Pro asset contains a number of simple drag and drop prefabs that you just need to drop into your UI canvas. Updating them is as simple as calling a simple method. And if you don't like the given bars, there's lots of flexibility in the scripts to quickly create your own with existing components or to extend it with new functionality.
    • 15 pre-designed progress bars and more to come...
    • Smooth bar animation
    • Preview of final value during animation
    • Change bar color based on fill value
    • Flash bar on value gain or loss
    • Dynamically placed text

    INTERACTIVE DEMO
    Play around with the bars and see how they behave

    The bar is currently on sale for it's launch discount. As I add more features, functionality and prefabs, the price will increase accordingly. So grab it now!

    Here's a look at the different visual options:


    And here's an overview over how to create your own bars:



    Known Issues

    If the bar is set to animate but you're updating it's value every frame the interpolation methods inherent to the animation will lead to the bar not moving properly towards it's new value. If you're updating regularly, simply deactivate the animate flag. This is something I'll look to solving in a future release.

    More coming soon, stay tuned.
     
    Last edited: Apr 3, 2017
  2. HellPatrol

    HellPatrol

    Joined:
    Jun 29, 2014
    Posts:
    38
    Looks great - bought it :)
     
  3. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Thanks! If you've got any questions, let me know. Same for feature requests or prefab bar ideas. Also if you've got time for a review, I'd greatly appreciate it!
     
  4. HellPatrol

    HellPatrol

    Joined:
    Jun 29, 2014
    Posts:
    38
    I already have a noob question:

    I use a standart Unity Slider for the Experience of the Player Character.
    The slider is updated like this:

    public SliderExpSlider;
    Code (CSharp):
    1. public void RefreshExp(int exp, int maxExp, bool ingoreMaxExp)
    2.         {
    3.             if (!ingoreMaxExp)
    4.             {
    5.                 ExpSlider.maxValue = maxExp;
    6.             }
    7.             ExpSlider.value = exp;
    8. }
    9.  
    My approach to use your Progress Bar:

    public ProgressBarPro ExpSlider;
    Code (CSharp):
    1.    public void RefreshExp(int exp, int maxExp, bool ingoreMaxExp)
    2.         {
    3.             if (!ingoreMaxExp)
    4.             {
    5.                 ExpSlider.SetValue(exp, maxExp);
    6.             }
    7.             ExpSlider.SetValue = exp;
    8.  }
    9.  
    Please don't laugh :p
     
  5. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Well it depends on what sort of values you expect, and how you want the behavor the behave when maxEXP are ignored. That is what's slightly confusing me. So everything within if (!ignoreMaxExp) looks good - you're updating with ints with a current and a max value.

    But the other one doesn't work. It'd either be "SetValue(exp)" but it then expects a value from 0-1 which doesn't really work there. I'm presuming you don't want to set a new maxExp value in that case? The solution would be to save the last maxExp value and use that in case of ignoreMaxExp. Sorta like:

    Code (CSharp):
    1. int lastMaxExp;
    2.  
    3. public void RefreshExp(int exp, int maxExp, bool ingoreMaxExp)
    4. {
    5.     if (!ingoreMaxExp)
    6.     {
    7.         ExpSlider.SetValue(exp, maxExp);
    8.         lastMaxExp = maxExp;
    9.     }
    10.     else {
    11.         ExpSlider.SetValue(exp, lastMaxExp);
    12.     }
    13. }
    This may or may not be the best solution to what you're trying to do.
     
  6. HellPatrol

    HellPatrol

    Joined:
    Jun 29, 2014
    Posts:
    38
    It works! Thank you Sir. Looks great in action :)
     
    Democide likes this.
  7. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Glad you enjoy it. As mentioned, if you find time to write a positive review, I'd greatly appreciate it!
     
  8. HellPatrol

    HellPatrol

    Joined:
    Jun 29, 2014
    Posts:
    38
    Done!
     
  9. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Much appreciated!
     
  10. John-G

    John-G

    Joined:
    Mar 21, 2013
    Posts:
    1,114
    Does this allow for circular fill sliders like a rev counter type fill.
     
  11. HellPatrol

    HellPatrol

    Joined:
    Jun 29, 2014
    Posts:
    38
    It allows circular bars.
    This is my result:
    Circular handles the exp and the horizontal health and stamina
     
    Last edited: Apr 3, 2017
    Democide and John-G like this.
  12. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Awesome looking stuff there! :D
     
  13. HellPatrol

    HellPatrol

    Joined:
    Jun 29, 2014
    Posts:
    38
    I have two questions:

    #1 I use the CircularSimple as my starting point. In the demo scene the handle is working fine. When i pick up the prefab the handle stop working. It just stays in the same place and i can't figure out why.

    //Edit: Ok, found that one. It has to be inside a Grid Layout Group

    #2 I replaced the Text compoment with TextMeshPro object. It works fine but throws errors at me:
    Code (CSharp):
    1. NullReference:
    2. PlayfulSystems.ProgressBar.BarViewValueText.UpdateView (Single target Value) (at .....BarViewValueText.cs:20)
     
    Last edited: Apr 5, 2017
  14. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Hey HellPatrol, it doesn't have to be in a layout group, but it's parent needs to be of the proper size for it to work. You may also have to work with the offset slider. The handle uses the size of it's parent to position itself. The CircularSimple root object is forced to be 256x256 by the GridLayout in the demo scene. It has to be that size even without the grid layout, then the BarHolder has the same size and the handle, that's a child of the BarHolder can then position itself accordingly. And if BarHolder would end up being width 0, height 0, the Handle can't animate.

    Make sense?

    And as for the second error: If you want to change the BarViewValueText from TEXT to TEXTMESHPRO, all you need to do is

    a) add the reference to TextMeshPro

    Code (CSharp):
    1. using TMPro;
    b) change line 9 (or so) from

    Code (CSharp):
    1. [SerializeField]Text text;
    to
    Code (CSharp):
    1. [SerializeField]TextMeshPro text;
    c) change line 57 (or so) from

    Code (CSharp):
    1. [SerializeField]text = GetComponent<Text>();
    to
    Code (CSharp):
    1. [SerializeField]text = GetComponent<TextMeshPro>();
    d) updated the reference in the gameObject to now point to your TextMeshPro object.
     
    John-G likes this.
  15. HellPatrol

    HellPatrol

    Joined:
    Jun 29, 2014
    Posts:
    38
    strange, i've done it that way. And it works, but I get this error at start. :(
     
  16. TanksZone

    TanksZone

    Joined:
    Aug 10, 2014
    Posts:
    128
    Hi, cool asset!

    Does it support Text Mesh Pro?
    I want to add advanced player name style to the health bar :)
     
  17. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    It should, but as HellPatrol mentioned he's been getting some issues.

    As said above, what you need to do is go into the "BarViewValueText" component and change all "Text" to "TextMeshProUGUI". Of course if you then use any of the prefabs they will be broken and you will have to restore them.

    An alternative would be to add a new BarViewValueTextMeshPro and use that on your own bar designs, or replace that in the prefabs you're using.
     
  18. Lars-Steenhoff

    Lars-Steenhoff

    Joined:
    Aug 7, 2007
    Posts:
    3,058
    Playmaker actions?
     
  19. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    I'm guessing you're asking if there's any available? Currently not. It'd be pretty easy to use with the existing playmaker actions as you only need to call a specific function on the progress bar with the 0-1 float as a parameter.
     
  20. Ghopper21

    Ghopper21

    Joined:
    Aug 24, 2012
    Posts:
    170
    Hi Martin, thanks for Progress Bar Pro. It's great overall!

    I do have a problem on Android. Sometimes (perhaps once every 5 or 10 times), the progress bar with glow will freeze right at the max glow. Then all Unity input will stop working, but the game continues running otherwise. Have you see this before?

    From web research, this is the closest possibly related thing I've found: https://answers.unity.com/questions/1184840/530occasionally-freeze-on-android-devices.html

    Any help much appreciated!
     
  21. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Hey Ghopper, that's the first time I hear about that. Have you tried on different devices?
     
  22. Ghopper21

    Ghopper21

    Joined:
    Aug 24, 2012
    Posts:
    170
    We've tried on two different devices. It does seems device specific. The device it's having problems on is a Motorola X 2nd Gen.
     
  23. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    What version of Unity are you running on?
     
  24. Ghopper21

    Ghopper21

    Joined:
    Aug 24, 2012
    Posts:
    170
    v5.6.3f1

    I will try on a more current version of Unity as soon as a I can, but unfortunately some unrelated project-specific issues make upgrading non-trivial for us.
     
  25. TanselAltinel

    TanselAltinel

    Joined:
    Jan 7, 2015
    Posts:
    159
    Can anyone confirm that this works on 2017.4?
     
  26. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    It should. I can grab the latest version of Unity and try it out here. Lemme do that.
     
  27. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Yeah works. Just tested.
     
    TanselAltinel likes this.
  28. MapMan

    MapMan

    Joined:
    Oct 27, 2013
    Posts:
    38
    Hey @Democide !

    I'm an associate of Ghopper21. We solved the issue we had. The fact that Unity input stopped working was just a symptom of an underlying issue in ProgressBarPro. Namely, the progress bar sometimes fails to 'finish' animating, and the IsAnimating() method returns true indefinitely. The reason why that happens is because sometimes the m_value is not equal to displayValue even though DoBarSizeAnim coroutine is finished. In DoBarSizeAnim after the while loop, the displayValue is set to m_value but it's without the force parameter. Thus, if Mathf.Approximately(displayValue, m_value) is true, displayValue won't be set to m_value and thus the subsequent comparison in IsAnimating() can possibly return true indefinitely.

    The easiest fix for this is to pass force = true in DoBarSizeAnim after the while loop. In general, it is always a bad idea to compare floats using the equality operators (https://stackoverflow.com/q/3874627). I think it would be a good idea to update the plugin not to compare floats like that to avoid problems in the future.
     
  29. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Thanks for the update! I'll give the issue a look!
     
  30. Saucyminator

    Saucyminator

    Joined:
    Nov 23, 2015
    Posts:
    49
    Hi Democide,

    Great asset!
    I've been doing something similar in my own project, but after getting stuck on both smoothly updating the animation (math is hard) and couldn't get the "shadow" work like I wanted I started to look for something else.
    Great price, no regrets buying your product. Simple to get it working, your youtube videos helped a lot too. Your bars are much better/cleaner looking as well - changing the anchor is something I didn't think of. Thanks!

    I have two feature ideas I hope you consider adding (maybe?):

    First:
    Adding "shadow" to the circle bars. Currently the shadow only works for bars if I'm correct? Having these for the circles would be awesome as well!
    I'm currently working on how to add this myself but I haven't delved deeply in your code yet.

    Second:
    I know this asset is only for health and progress bars. An EXP bar is kind of a progress bar and adding a behavior to the progress bars could be good to have in the asset.

    The behavior:
    If the progress is at 0f (0%) and the player gains 150% EXP. That means the progress value should animate to 1f (100%), reset with no animation to 0f (0%), then animate again to 0.5f (50%).
    (No idea how AAA games or professional programmers do this, but this is how I think it works.)

    These are my scripts/my edits to your scripts to make the EXP bar work in my project. Normally I don't like changing assets scripts because one update and it can break.

    My class for updating the value on the bar/circle:

    DebugUpdateValue.cs
    Code (CSharp):
    1. public class DebugUpdateValue : MonoBehaviour {
    2.   public ProgressBarPro progressBarPro;
    3.   public float progress; // Current EXP progress, has a percentage value between 0-1
    4.  
    5.   public void UpdateValue () {
    6.     // Checks if player has level up (currently has no code for this yet, let's pretend it is working)
    7.     if (hasLeveledUp) {
    8.       StartCoroutine(LeveledUp());
    9.     } else {
    10.       progressBarPro.SetValue(progress);
    11.     }
    12.   }
    13.  
    14.   // My very simple yet hacky solution
    15.   IEnumerator LeveledUp () {
    16.     progressBarPro.SetValue(1f); // Fill the bar with animation
    17.     yield return progressBarPro.SizeAnim; // Waits for the animation to finish
    18.     progressBarPro.SetValueNoAnimation(0f); // Resets value without any animation
    19.     progressBarPro.SetValue(progress); // Normal animation call
    20.   }
    21. }
    Changes made to ProgressBarPro script file:

    ProgressBarPro.cs
    Code (CSharp):
    1. public class ProgressBarPro : MonoBehaviour {
    2.   ...
    3.   // Added property:
    4.   public Coroutine SizeAnim { get { return sizeAnim; } }
    5.   ...
    6.   // Added method, hacky but works:
    7.   public void SetValueNoAnimation (float percentage) {
    8.     animateBar = false;
    9.     SetValue(percentage);
    10.     animateBar = true;
    11.   }
    12. }
     
  31. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Some good suggestions! Thank you :)

    The issue with the shadow on the circles is that the default image component, which is used to fill the circular bar can not set a start and an end point, only fill in from one end. This makes shadows, which are sections along the bar, impossible without creating a variant of the image component that allows that, something I was trying to avoid.

    The XP reset thing seems useful, but I think that's something I'd create outside the bar. so when there's a level up, the bar is cleared and then set to the new size by whatever manages the level up.
     
  32. Gua

    Gua

    Joined:
    Oct 29, 2012
    Posts:
    438
    @Democide Seems like a good and polished asset. I have a feature suggestion. Could you add option to animate the size of health bar on value change. Like the one you can see in this video. Adding option to shake it on value change would be also good.

     
    Last edited: Mar 18, 2019
  33. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Ask and ye shall receive! The following code does exactly what you're looking for.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5. namespace PlayfulSystems.ProgressBar {
    6.     [RequireComponent(typeof(RectTransform))]
    7.     public class BarViewScale : ProgressBarProView {
    8.  
    9.         [SerializeField] protected RectTransform graphic;
    10.  
    11.         [Header("Color Options")]
    12.         [Tooltip("If true, then the scale animates for each change. Otherwise it scales constantly based on value")]
    13.         [SerializeField] bool animateOnChange = true;
    14.  
    15.         [SerializeField] Vector3 minSize = Vector3.one;
    16.         [SerializeField] Vector3 maxSize = new Vector3(2f, 2f, 2f);
    17.         [Tooltip("A value of 0 is minSize, a value of 1 is maxSize. Time goes from 0 to 1.")]
    18.         [SerializeField] AnimationCurve scale;
    19.         [SerializeField] float animDuration = 0.2f;
    20.  
    21.         private Coroutine scaleAnim;
    22.  
    23.         void OnEnable() {
    24.             UpdateScale();
    25.         }
    26.  
    27.         public override void NewChangeStarted(float currentValue, float targetValue) {
    28.             if (gameObject.activeInHierarchy == false || !animateOnChange)
    29.                 return; // No Coroutine if we're disabled
    30.  
    31.             if (scaleAnim != null)
    32.                 StopCoroutine(scaleAnim);
    33.  
    34.             scaleAnim = StartCoroutine(DoBarScaleAnim(animDuration));
    35.         }
    36.  
    37.         IEnumerator DoBarScaleAnim(float duration) {
    38.             float time = 0f;
    39.  
    40.             while (time < duration) {
    41.                 UpdateScale(time / duration);
    42.                 time += Time.deltaTime;
    43.                 yield return null;
    44.             }
    45.  
    46.             UpdateScale(0f);
    47.             scaleAnim = null;
    48.         }
    49.  
    50.         public override void UpdateView(float currentValue, float targetValue) {
    51.             if (animateOnChange)
    52.                 return;
    53.  
    54.             if (scaleAnim == null) // if we're flashing don't update this since the coroutine handles our updates
    55.                 UpdateScale(currentValue);
    56.         }
    57.  
    58.         void UpdateScale(float value = 0f) {
    59.             graphic.localScale = GetCurrentScale(value);
    60.         }
    61.  
    62.         Vector3 GetCurrentScale(float percentage) {
    63.             return Vector3.Lerp(minSize, maxSize, scale.Evaluate(percentage));
    64.         }
    65.  
    66. #if UNITY_EDITOR
    67.         protected override void Reset() {
    68.             base.Reset();
    69.  
    70.             graphic = GetComponent<RectTransform>();
    71.         }
    72.  
    73.         void OnValidate() {
    74.             UpdateScale();
    75.         }
    76. #endif
    77.     }
    78.  
    79. }
     
    StevenPicard, Gua and TanselAltinel like this.
  34. IronVultureTeam

    IronVultureTeam

    Joined:
    Feb 8, 2017
    Posts:
    1
    Hi Democide,
    I just bought the asset, it works really well. Appreciate!

    Is there a way to add various size tick on the bar in this asset?

    (like this)
     
  35. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Well the simplest thing is to manually lay those ticks over the bar itself. Simply make one sprite that repeats appropriately and put it over the bar. However if you want the bar to then only snap to those thicknesses you need to use the defined step size, but that doesn't play well with different sized ticks. Still if the ticks are above the bar you might be able to tweak it so it still lines up.

    Does that help?
     
  36. Gua

    Gua

    Joined:
    Oct 29, 2012
    Posts:
    438
    @Democide
    Thanks! But can you give me more details on how to properly use this? Should I put it as seperate script wit name ProgressBar? How to properly hook it to progress bar?
     
  37. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    It's a custom script called "BarViewScale.cs". Then put it onto the thing you want to scale and make sure the progressbar links to it.
     
    StevenPicard and Gua like this.
  38. Gua

    Gua

    Joined:
    Oct 29, 2012
    Posts:
    438
    There is one more feature I would love to see. I would love to see optional delay time, for shadow decrease animation. This option will delay shadow decrease animation so that player could see a full impact of his action. Nowadays it's practically a standard for a lot of health bars.

    You can see it here at the bottom.


    Here's another example. Bottom left.



    Right

     
    Last edited: Jan 14, 2020
  39. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    This is a more complex tweak. I'll put it on the list but it might take a bit until I'll have time to get to it. A bunch of other things on my plate right now.
     
    Gua likes this.
  40. Gua

    Gua

    Joined:
    Oct 29, 2012
    Posts:
    438
    I'm just glad it will be implemented sometime in the future. I've tried to add it myself, but it's beyond my skill level. (I mostly write game logic in Playmaker, so my C# skills are pretty limited.)
     
  41. Jiinzu

    Jiinzu

    Joined:
    Jan 18, 2019
    Posts:
    8
    Hi, i would like to be sure i can't set up a health bar for a RPG?! that mean access max value for increase max health with another script?
     
  42. Gua

    Gua

    Joined:
    Oct 29, 2012
    Posts:
    438
    Can you give at least super rough ETA on that feature?
     
  43. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Sorry, I'm super busy with life right now and can't give na ETA.

    As for Jinzu's questions: you can increase the max health of the bar over time. Simply when you update the bar you need to let it know how much of which maximum, and the bar will update accordingly.
     
  44. bpodell

    bpodell

    Joined:
    Nov 11, 2017
    Posts:
    3
    Awesome bars! Thanks for the great asset!

    I'm trying to change the FillType to RightToLeft using C# code when a value is positive, and LeftToRight when the value is negative. Does anyone have any ideas?

    Below is my code, where line 2 is returning an error because I'm unsure what component to add to reference the FillType.

    Code (CSharp):
    1. public GameObject HomeNetBar;
    2. HomeNetBar.GetComponent<ProgressBarPro>.FillType = RightToLeft;
    Below is the class that stores the FillType variable.

    Code (CSharp):
    1. namespace PlayfulSystems.ProgressBar {
    2.     [RequireComponent(typeof(RectTransform))]
    3.     public class BarViewSizeAnchors : ProgressBarProView {
    4.  
    5. public enum FillType { LeftToRight, RightToLeft, TopToBottom, BottomToTop };
     
    Last edited: Aug 15, 2020
  45. Democide

    Democide

    Joined:
    Jan 29, 2013
    Posts:
    312
    Try something like this:

    Code (CSharp):
    1. public GameObject HomeNetBar;
    2.  
    3. var sizeAnchor = HomeNetBar.GetComponentInChildren<BarViewSizeAnchors>();
    4.  
    5. if (sizeAnchor != null)
    6.    sizeAnchor.fillType = RightToLeft;
     
  46. bpodell

    bpodell

    Joined:
    Nov 11, 2017
    Posts:
    3
    I got it working and figured out 2 ways, thanks!

    I had to change protected to public in the BarViewSizeAnchors script.

    Code (CSharp):
    1. //Changed protected to public in BarViewAnchors Script
    2. public enum FillType { LeftToRight, RightToLeft, TopToBottom, BottomToTop };
    3.  
    4. //Code in main script
    5. public GameObject HomeNetBar;
    6.  
    7. HomeNetBar.GetComponentInChildren<PlayfulSystems.ProgressBar.BarViewSizeAnchors>().fillType = PlayfulSystems.ProgressBar.BarViewSizeAnchors.FillType.RightToLeft;

    Code (CSharp):
    1. //Alternate Method
    2. //Create function in BarViewSizeAnchors Script
    3. public void ChangeFillType(int Type)
    4.         {
    5.             switch(Type)
    6.             {
    7.                 case 0:
    8.                     fillType = FillType.LeftToRight;
    9.                     break;
    10.                 case 1:
    11.                     fillType = FillType.RightToLeft;
    12.                     break;
    13.             }
    14.         }
    15.  
    16. //Code in main script.
    17. var sizeAnchor = HomeNetBar.GetComponentInChildren<PlayfulSystems.ProgressBar.BarViewSizeAnchors>();
    18. sizeAnchor.ChangeFillType(0);
     
  47. cptscrimshaw

    cptscrimshaw

    Joined:
    Aug 20, 2020
    Posts:
    3
    Hi there, absolutely love your progress bar script. It's simple, and it works! Quick question - I ran into an issue where something in the code is updating the position of my bar in the editor. I dug through the code a bit, but didn't want to change too much in case there was something I was doing wrong in the inspector setup. When I reset the Top and Bottom of the bar in the inspector, it goes back to the correct place, but it seems like when I am updating other prefabs in an around this one, it will move the bar position back to -167/+167... any ideas?

    Screen Shot 2020-10-11 at 10.14.34 PM.png

    Thanks!
     
  48. xpxilom

    xpxilom

    Joined:
    Aug 28, 2014
    Posts:
    29
    Puedes volver a poner el video, no carga.
     
  49. Gua

    Gua

    Joined:
    Oct 29, 2012
    Posts:
    438
     
    xpxilom likes this.
  50. UnityZaki

    UnityZaki

    Joined:
    Jan 10, 2018
    Posts:
    17
    Please i need your help.this my original script health bar for my game and i want to use health and progress bar pro.how can change my script
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. [RequireComponent(typeof(Slider))]
    5. public class UIHUDHealthBar : MonoBehaviour {
    6.  
    7.     public Text nameField;
    8.     public Image playerPortrait;
    9.     public Slider HpSlider;
    10.     public bool isPlayer;
    11.  
    12.     void OnEnable() {
    13.         HealthSystem.onHealthChange += UpdateHealth;
    14.     }
    15.  
    16.     void OnDisable() {
    17.         HealthSystem.onHealthChange -= UpdateHealth;
    18.     }
    19.  
    20.     void Start(){
    21.         if(!isPlayer) Invoke("HideOnDestroy", Time.deltaTime); //hide enemy healthbar at start
    22.         if(isPlayer) SetPlayerPortraitAndName();
    23.     }
    24.  
    25.     void UpdateHealth(float percentage, GameObject go){
    26.         if(isPlayer && go.CompareTag("Player")){
    27.             HpSlider.value = percentage;
    28.         }    
    29.  
    30.         if(!isPlayer && go.CompareTag("Enemy")){
    31.             HpSlider.gameObject.SetActive(true);
    32.             HpSlider.value = percentage;
    33.             nameField.text = go.GetComponent<EnemyActions>().enemyName;
    34.             if(percentage == 0) Invoke("HideOnDestroy", 2);
    35.         }
    36.     }
    37.  
    38.     void HideOnDestroy(){
    39.         HpSlider.gameObject.SetActive(false);
    40.         nameField.text = "";
    41.     }
    42.  
    43.     //loads the HUD icon of the player from the player prefab (Healthsystem)
    44.     void SetPlayerPortraitAndName(){
    45.         if(playerPortrait != null){
    46.             GameObject player = GameObject.FindGameObjectWithTag("Player");
    47.             HealthSystem healthSystem = player.GetComponent<HealthSystem>();
    48.  
    49.             if(player && healthSystem != null){
    50.  
    51.                 //set portrait
    52.                 Sprite HUDPortrait = healthSystem.HUDPortrait;
    53.                 playerPortrait.overrideSprite = HUDPortrait;
    54.  
    55.                 //set name
    56.                 nameField.text = healthSystem.PlayerName;
    57.             }
    58.         }
    59.     }
    60. }
    61.  
     
unityunity