Unity noob here, in the process of creating a 3D survival game. I wrote a script which handles player’s health, energy and stamina which I’ll paste below. Now, I would like to attach it to a UI health bar so the stat value dropping or increasing is visible to the player. How can I create a UI element and attach my script to it for this to work?
for future questions there is a little icon with 1’s and zeros above where you type your question within this website to post code so you dont have to use a third party “paste code site”. anyways, here is a simple health bar. good luck to you!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttributesc : MonoBehaviour {
//Attributes
public static float health, stamina, energy,percent;
public float maxHealth, maxStamina, maxEnergy;
public Texture2D back;
public Texture2D line;
void OnGUI(){
GUI.DrawTexture (new Rect (5, 5, 200,20), back);
percent = health / maxHealth;
if (percent > 0) {
GUI.DrawTexture (new Rect (8, 8, 194 * percent, 14), line);
}
}
void Start()
{ maxHealth = 10;
back = new Texture2D (1, 1);
line = new Texture2D (1, 1);
back.SetPixel (0, 0, Color.black);
line.SetPixel (0, 0, Color.green);
back.Apply ();
line.Apply ();
health = maxHealth;
stamina = maxStamina;
energy = maxEnergy;
}
void Update()
{
Debug.Log(health + "Health"); //Decrease health
if (health <= maxHealth)
health -= 0.5f * Time.deltaTime; //per second
if (health <= 0) //Player death after health drops to 0
death();
if (health <= 0)
print("You died. Remember, you need food to survive.");
//---------------------------------------------------------------------------------------------------------//
print(energy + "Energy"); //Decrease energy
if (energy <= maxEnergy)
energy -= 1f * Time.deltaTime; //per second
if (energy <= 0) //Player death after energy drops to 0
death();
if (energy <= 0)
print("You died. Remember, you need sleep to survive.");
//---------------------------------------------------------------------------------------------------------//
print(stamina + "Stamina"); //Decrease stamina if sprinting FIX
if (Input.GetKey(KeyCode.LeftShift) && stamina > 0)
{
stamina -= 10f * Time.deltaTime;
}
else
{
stamina += 2f * Time.deltaTime;
}
if (stamina <= 0)
print("You ran out of stamina. Wait a moment before sprinting again.");
}
void death(){
}
}