5

I am currently working on a healthbar which slowly drains the less health you have. I followed this tutorial to get the healthbars I wanted: https://www.youtube.com/watch?v=NgftVg3idB4

In short, it uses a mask layer and a seperate green bar to indicate the amount of health. By moving the green bar to the left, it disappears behind the mask layer and thus shows less and less health. The method to calculate its position based on the amount of health is here: Code (CSharp):

float maxXValue = healthTransform.position.x;
float minXValue = healthTransform.position.x - healthTransform.rect.width;

private void HandleHealth()
{
    Stats attachedStats = attachedObject.GetComponent<Stats>();

    float currentXValuePlayer = MapValues(attachedStats.currentHealth, 0, attachedStats.maxHealth, minXValue, maxXValue);
    healthTransform.position = new Vector3(currentXValuePlayer, cachedY);
}

private float MapValues(float x, float inMin, float inMax, float outMin, float outMax)
{
    return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}
/*
EXPLANATION:
attachedStats.currentHealth is the current health the player has
attachedStats.maxHealth is the maximum amount of health the player can have
minXValue is the furthest left point the bar is at when health is 0
maxXValue is the furthest right point the bar is at when health is full
*/

This is the setting I use for the canvas the healthbar is drawn on. [​IMG]

The trouble is(probably) that because of the scaling the canvas does, healthTransform.rect.width still returns the original size of the healthbar and not the new, scaled size. So is there a way to find out how much the Canvas Scaler has scaled things?

3 Answers 3

11

I asked the same question back in December on the Unity forums:

http://forum.unity3d.com/threads/canvasscaler-current-scale.285134/

The answer from Unity was: "After the canvas has been scaled you should be able to just read it back from the scaleFactor on the canvas as the canvas scaler just controls this value. "

But, no matter how small the UI gets, the value of scaleFactor is always 1.0. I don't know why this is, and Unity never responded again. Has anyone else had any luck being able to extract this value?

As a workaround, The RectTransform's localScale on the object you have CanvasScaler script on should reflect the current scale of the entire UI.

1
  • 1
    Thank you so very much! This was exactly my problem, I was already wondering what the scaleFactor was for really. But thanks a ton, this had me stumped for quite a while, you just made my day!
    – Lionlake
    Jan 8, 2015 at 19:27
3

There is an easier way of handling the width of the green bar - which is to make it a "Filled" image type. That way you don't need masks at all, which simplifies things quite a bit.


Creating a healthbar in Unity 4.6+ using filling

Create a canvas object that contains the images you need (in this case, the red background bar, the green foreground bar and the outline).

enter image description here

When placed in this order, the lowest image will appear on top (see below).

enter image description here

The result will be a healthbar that looks like this:

enter image description here

However, now we need to be able to control the width of the green bar based on the amount of hit points. In order to do this we can modify the image component of "Green Bar":

  • Change Type to "filled"
  • Change Fill Method to "Horizontal"
  • Change Fill Origin to "Left".

enter image description here

It is now possible to control the width of the green bar by modifying the Fill Amount. (You can test it with the slider)

Finally you must add a script that sets the width of the green bar which could look like the following in C#:

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

public class HealthBar : MonoBehaviour {

    public float MaxHealth = 100;
    private float _playerHealth;
    private Image _greenBar

    void Start () {
            _playerHealth = MaxHealth;
            _greenBar = transform.FindChild("GreenBar").GetComponent<Image>();
    }

    void Update () {

            //logic to set _playerHealth goes here

            _greenBar.fillAmount = _playerHealth/MaxHealth;
    }
}
1

I encountered exactly this problem today (some three years after the question was asked) and found that by using scaleFactor on the Canvas object in both Start() and Update(), I was able to get the proper factor for scaling the mask movements. However, it seems that the value is not reliably set in Awake(), which may have caused some grief.

For future reference, you do not need any kind of workaround for this, as was suggested in Farmer Joe's answer. If there ever was a bug--which I doubt--it has been fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.