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.

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)

		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


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.

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.