Updating stamina in UISlider

Hi all,

I’m fairly new to Unity (and coding in general), so please bare with me.

I’ve created a very basic environment for an RPG, to which I am adding functionality as a way of learning new concepts.

At present, I’m trying to add a UISlider to reflect the characters stamina. The stamina needs to fall as the player holds left shift, and regenerate when they release the key. I have set up the canvas, and positioned the slider. I have created a ‘PlayerStats’ script to hold the logic, and attached it to the player.

My problem is that the bar does not update when I use time.deltaTime - but does when I use time.time - which doesn’t seem appropriate. Also, changing the float values of staminaFallRate and staminaIncreaseRate has no effect on the speed of the decrease/increase?

It would be really great if someone could please be so kind as to lend their thoughts :slight_smile:

Since I am a true beginner, I ask you to also point out any other shortfalls/floors/inefficiencies in my syntax! Thank you!

public class PlayerStats : MonoBehaviour {

	public int startingHealth = 100;
	public int currentHealth;

	public float startingStamina = 100f;
	public float currentStamina;
	public float staminaFallRate = 150f;
	public float staminaIncreaseRate = 2f;

	public int startingArcane = 100;
	public int currentArcane;

	public Slider healthBar;
	public Slider staminaBar;
	public Slider manaBar;
	public Image playerHurtImage;
	public AudioClip deathClip;
	public float flashSpeed = 5f;
	public Color flashColor = new Color (1f, 0f, 0f, 0.1f);

	AudioSource playerAudio;
	ThirdPersonCharacter thirdPersonCharacter; // Used to stop player from running around once they are dead.
	bool isDead;
	bool damaged;
	bool isRunning;

	void Awake()
	{
		thirdPersonCharacter = GetComponent<ThirdPersonCharacter>(); // Third person character is name of script we are getting.
		playerAudio = GetComponent<AudioSource>();
		currentHealth = startingHealth;
		currentStamina = startingStamina;
		staminaBar.value = currentStamina;
		currentArcane = startingArcane;

	}

	void Update()
	{

		if(Input.GetKey(KeyCode.LeftShift))
		{
			currentStamina -= Time.time / staminaFallRate;
			staminaBar.value = currentStamina;
		} 
		else if (currentStamina < startingStamina)
		{
			//staminaBar.value = Mathf.MoveTowards(currentStamina, startingStamina, 2f);
			currentStamina += Time.time / staminaIncreaseRate;
			staminaBar.value = currentStamina;
		}

		if (currentStamina >= startingStamina)
		{
			currentStamina = 100;
		}
	}

Please Don’t forget Import UI At Top Of Your Code :

import UnityEngine.UI;

I Use This Code For Changing The Value Of Slider And Its Works Fine :

var HealthSlider : GameObject; // The Slider
var Life : int = 100; // Health Of Enemy

function FixedUpdate()
{ HealthSlider.GetComponent(Slider).value = Life; }

Don’t Forget : check The “Whole Numbers” Property In Slider If Your Variable Is Int (Like ME)

Hope Its Help :slight_smile: