C# script to make simple UI Health/Progress/Loading/… Bar.

Scripts:

HealthController:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// © 2017 TheFlyingKeyboard
// theflyingkeyboard.net

public class HealthController : MonoBehaviour {
    public HealthBarController healthBar;

    public float healthChange;

    void Update() {
        if (Input.GetKey(KeyCode.W))
        {
            healthBar.health += healthChange;
        }

        if (Input.GetKey(KeyCode.S))
        {
            healthBar.health -= healthChange;
        }
    }
}

 

HealthBarController:

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

public class HealthBarController : MonoBehaviour {
    //Access this variable from your script or add proper function in this script 
    public float health;
    public float minHealth;
    public float maxHealth;

    private Slider healthBar;

    private void Start()
    {
        healthBar = GetComponent<Slider>();
    }

    void Update () {
        UpdateHealthBar();

        health = Mathf.Clamp(health, minHealth, maxHealth);
    }

    void UpdateHealthBar()
    {
        healthBar.value = health;
    }
}

 

Add UI slider to the scene and set properties as shown below

Then add gameobject with propeties:

Unity C# UI Health/Progress/Loading/… Bar
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.