What am I doing wrong? Using mathf.clamp to cap an int value. value

Hi. This may be obvious to some however being relatively new to using C# I am finding it hard sometimes to achieve something simple. I am making a stamina system for my project/game. I have it decreasing and increasing which is great, but it increases past the a point I wish to stop it at.

I want my stamina in this case to be capped at 200 but it recovers way beyond that. I also want my stamina NOT to fall below 0 but it seems to if I hold shift long enough. I think using mathf.clamp is the right solution but sure on the execution of it.

My problem lies in the (canRegen). I want stamina to recover at a steady 60 units a second up-to 200 and then stop. I assume the same could be used to have a min for stamina of 0 so that it cannot fall below 0.

Any help is greatly appreciated as always as this is for uni. Thank you for your time.

using UnityEngine;
using System.Collections;

public class stamina : MonoBehaviour {
public static float maxStaminaValue = 200.0f;
public static float currentStaminaValue;
public static float decreasingStaminaValue = 50.0f;
public static float recoveringStaminaValue = 70.0f;
public static bool isSprinting = false;
public static bool canRegen = false;

// Use this for initialization
void Start () {
	currentStaminaValue = maxStaminaValue;

// Update is called once per frame
void Update () {
	if (Input.GetKeyUp (KeyCode.LeftShift)) {
		print ("is not pressed");
		isSprinting = false;
		canRegen = true;

	if (Input.GetKeyDown (KeyCode.LeftShift)&& currentStaminaValue > 0) {
		print("is pressed");
		isSprinting = true;
		canRegen = false;

	if (isSprinting) {
					currentStaminaValue -= decreasingStaminaValue * Time.deltaTime;
					Player.playerSpeed = 15.0f;
			} else {
		Player.playerSpeed = 5.0f;

	if (canRegen) {
		if (currentStaminaValue != maxStaminaValue){
			float regenAmount = Mathf.Clamp (60.0f, 0.0f, 200.0f);
			print("regenAmount is " + regenAmount);
			currentStaminaValue += regenAmount * Time.deltaTime;


I fixed this myself. Didn’t even have to use mathf.clamp just a case of proper if statements using <=0 and < to achieve what I wanted. :slight_smile:

if (currentStaminaValue < maxStaminaValue){
instead of if (currentStaminaValue != maxStaminaValue)
if (currentStaminaValue <= 0) {
This gave me the desired results