- Home /
Dynamic slider size with the new UI
Hello, I'm quite new at Unity and programming and now I'm having problem at displaying a dynamic size HP Bar. What I want to achieve is a HP Bar that the length scales with the maximum HP variable (By script). These pictures should explain these more..
These can be achieved by manually modifying the "Right" value in Rect Transform inspector. But through script I have no idea. I've tried modifying localscale values but come with no luck. Thank you.
Answer by furibaito · Dec 27, 2014 at 06:03 AM
I've solved my problem, here is the solution if anyone else need it.
public float PlayerMaxHP = 50;
public GameObject HPSlider;
void Start ()
{
RectTransform HPSliderRect= HPSlider.GetComponent<RectTransform>();
HPSliderRect.sizeDelta = new Vector2(PlayerMaxHP, HPSliderRect.sizeDelta.y);
}
The value that I need to change is .sizeDelta on the RectTransform component of the HPSlider gameobject.
Answer by Mmmpies · Dec 26, 2014 at 09:06 AM
If I'm right the you want the HP slider to be the same size no matter how much HP you have so
HP = 200 HP bar size = ############## HP = 100 HP bar size = ##############
is that right?
If so this is what I do with my player health script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public static float maxHealth = 200;
public static float curHealth = 100;
public float restoreHealth = 0.5f; // how much to restore health per second
public GameObject HUDUICanvas;
public GameObject HealthBar;
public Slider HSlider;
private string _loadedLevel;
// Use this for initialization
void Start () {
HUDUICanvas = GameObject.FindGameObjectWithTag("UI");
HealthBar = GameObject.FindGameObjectWithTag("HealthBar");
HSlider = HealthBar.GetComponentInChildren<Slider>();
}
// Update is called once per frame
void Update () {
if (curHealth < maxHealth)
{
AdjustCurrentHealth(restoreHealth * Time.deltaTime);
}
}
public void AdjustCurrentHealth(float adj)
{
curHealth += adj;
if(curHealth < 0)
curHealth=0;
if(curHealth > maxHealth)
curHealth = maxHealth;
if(maxHealth < 1)
maxHealth = 1;
HSlider.value = (curHealth / maxHealth);
if(curHealth == 0)
{
Debug.Log(" I'm dead.");
}
}
}
The maxHealth and CurHealth can be any number, I then find the
<slider>
component and store in HSlider.
When the health is adjusted I set the HSlider.value = (curHeath / maxHealth).
All it does is make it display the curHealth as a % of the maxHealth so the maximum size of the slider is 100.
Sorry, but what I need is to make the HP slider to be different size when the value $$anonymous$$axHP is different. Thanks though for the answer
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Unity 4.6: GetComponent().onClick... how do you add an event to button click? 6 Answers
How to create a gradient progress bar 3 Answers
Get UI Slider Value 3 Answers
Trying to move slider based off percentage of screen 1 Answer