How to create a health bar using Ugui

Source: Internet
Author: User


Idea

Ugui system, there are some cool things like masking and canvas rendering in world space. We will first create a canvas, a health bar border, a mask and an image, representing the unit of health. Then we use some script to connect the cells (we'll use Observer pattern).

Set up our graphics

First thing first-let's create some graphics.

We want to have a holding object with only one Collider collider, a rigid body rigidbody, and some enemy script (now let's take it to something abstract). You should first add a "Canvas" sub-object and set it to render mode to World Space, choosing your main camera:

You should then add the healthframe image as a child of this object. After that, another child image object adds a mask component to it. Then add another image as a child of this mask . This image sets the masked property correctly.

Canvas-the width and height are: [0.2, 0.04], the Raycaster component is removed (we don't need it at all).
Healthframe-set anchor to full stretch and set the margin margins to 0.
Healthmask-set anchor to horizontal stretch, set left and right margin margins to 0.01 (0.00999989 or 0.010003 or other, it may have minor errors-it is due to floating The rounding error in point format.
healthbar-any width and height (as long as it is larger than the mask), content beyond masked will not be displayed.


These properties will work at any resolution resolution, and we'll set the render mode on the canvas to World Space. These values are actually in units and not in pixels. You should have such a thing right now:

Script writing

Now, the most interesting part-the script. We want to change the fill rate for the health bar based on our current health. Let's simplify, except for the health of our code in the logic of not doing anything.

Let's create a health script and put it in our main container (mob or unit). Its contents will look like this:

public class Health:monobehaviour {[Serializefield] private float _maxhealth = 100f;  Public float Currenthealth {get; set;}}


The [Serializefield] and private float fields let us adjust this value through inspector without breaking any encapsulation. The Currenthealth property will actually be used in our game in real time (so the _maxhealth field does not change).
Now let's add a void Start () method. Now, I'll just copy the _maxhealth value to the Currenthealth property.

public class health:monobehaviour{  ... void Start ()  {    currenthealth = _maxhealth;  } ...}

Now drag this script into the unit/mob (and change it Max Health if you want)
Now, we need a script on our health bar. Let's call it HealthBarRenderer .

public class healthbarrenderer:monobehaviour{  private health _healthscript;  void Start ()  {    _healthscript = getcomponentinparent

Or you can make this public field (or Serializefield private) and put the health script. The script should also have a link to the canvas and mask, so it can manipulate the size of the mask depending on the canvas's maximum width. We will drag and drop the script with the canvas object, so we can get our component as follows:

public class healthbarrenderer:monobehaviour{  private health _healthscript;  Private Recttransform _maskrecttransform;  void Start ()  {    _healthscript = getcomponentinparent

Copy the health field for the canvashealthbar object,

Observer pattern

Control health Bar directly from the health script it's not a good idea. It will eventually become very large and difficult to maintain. Fortunately, there is also the Observer mode. Its full meaning is to create the event dispatcher and its listeners (or observers). Dispatcher was ignorant of its observers, only to inform them of what had happened. It creates a lot of loose coupling. Our enemy should not know anything about the health of any health bars present it.

Let's create our event in the health script so that the health itself changes. The health class will now look like this:

public class health:monobehaviour{  [Serializefield]  private float _maxhealth = 100f;   private float _currenthealth;  Public float currenthealth  {    get {return _currenthealth;}    Set    {      _currenthealth = value;      if (healthchangedevent! = null)      {        healthchangedevent (_maxhealth, _currenthealth)      ;  }}} Public event action<float, float> healthchangedevent;   void Start ()  {    currenthealth = _maxhealth;  }}

Look at the Currenthealth property. Its setter has some extra logic. It will trigger a newly created healthchangedevent with two parameters-_maxhealth and _currenthealth. So different observers observers can do any of these values that they want to use. So we'll need to calculate the percentage.

in theWe HealthbarPreparewe arewill beNeed Healthcan becorrectchange Mask of thewidthof thethan

You can also pass a unique parameter-the current percentage, but in this example we will pass two parameters. That's it, we won't do anything more with this kind.
So let's go back to our healthbarrenderer script. We will add an event listener listener, and we will update the current width of our mask.

public class healthbarrenderer:monobehaviour{  private health _healthscript;  Private Recttransform _maskrecttransform;  private float _maxwidth;   void Start ()  {    _healthscript = getcomponentinparent

First, we subscribe to the health script event. Please note that our event listeners have the same signature as this event itself. In this event listener we calculate our proportions and change the recttransform width of our mask according to this value. Now, if you change the health script through its properties in health, it will automatically change the width of our mask:



Finally, it is important to say that mask plays a role, before the health bar is a two-part foreground and background. The foreground uses the nine Gongge format so that the scaling is not distorted,

Now you don't have to worry about this with mask. There's a difference!



??

How to create a health bar using Ugui

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.