Issue Coding Stamina Bar

I’m Trying to make a stamina bar for a survival game I’m working on. As far as I can tell my code works but I have one small issue that I feel will cause problems if not addressed now.
I have a scriptable obj for all the players stats so, stamina( being the max stamina) and staminaCurrent (for the current possible stamina that can be regenerated). and then the script that effects the stamina bar and how much is displayed and used at any time. there is a function that passively depletes the stamina and displays this (staminaCurrent) this all works fine the problem is that when I press LeftShit for the first time to run, if the current Stamina is less than the max, the stamina bar shoots up to the max stamina position then decreases from the max. now if I hold shift and let it deplete past the staminaCurrent declared in the scriptable obj then press shift the bar depletes from where it currently is and recharges to staminaCurrent like i want it too.
so my question is dose anyone know why it shoots up to the top the first time I press shift. thankyou in advance
also sorry I’m still somewhat new to coding and I’m sure there was a better way to approach what I’ve done so far but heres the code

public Slider staminaBar;
   
    private int currentStamina;

    public static StaminaBar instance;

    private WaitForSeconds regenTick = new WaitForSeconds(0.1f);
    private Coroutine regen;

    public bool isDepleated = false;

    public PlayerStatsSOBJ objStamina;

    private void Awake()
    {
        instance = this;
    }

    void Start()
    {
        currentStamina = objStamina.staminaCurrent;
        staminaBar.maxValue = objStamina.staminaCurrent;
        staminaBar.value = objStamina.staminaCurrent;

        InvokeRepeating("passiveStaminaDepleation", 1.0f, 1.0f);
    }
   
    public void Update()
    {
        if (currentStamina <= 0)
        {
            isDepleated = true;
            Debug.Log("no Stamina");
        }
        if (currentStamina >= 1 && isDepleated == true)
        {
            isDepleated = false;
            currentStamina += objStamina.staminaCurrent / objStamina.staminaCurrent;
            staminaBar.value = currentStamina;

            if (regen != null)
                StopCoroutine(regen);

            regen = StartCoroutine(RegenStamina());
            Debug.Log("Stamina at 1");
        }
    }

    public void UserStamina(int amount)
    {
        if (currentStamina - amount >= 0 && isDepleated == false)
        {
            currentStamina -= amount;
            staminaBar.value = currentStamina;

            if (regen != null)
                StopCoroutine(regen);

            regen = StartCoroutine(RegenStamina());
        }
      
    }
  
    private IEnumerator RegenStamina()
    {
        yield return new WaitForSeconds(2);
        while(currentStamina < objStamina.staminaCurrent && isDepleated == false)
        {
            currentStamina += objStamina.staminaCurrent / objStamina.staminaCurrent;
            staminaBar.value = currentStamina;
            yield return regenTick;
        }
        if (currentStamina <= 0)
        {
            Debug.Log("Stamina Depleated");
            yield return new WaitForSeconds(2);
            while (currentStamina < objStamina.staminaCurrent && isDepleated == true)
            {
                currentStamina += objStamina.staminaCurrent / objStamina.staminaCurrent;
                staminaBar.value = currentStamina;
                yield return regenTick;
            }
        }
        regen = null;
    }

    private void passiveStaminaDepleation()
    {
        if (currentStamina > 10)
        {
            staminaBar.value -= 1;
            objStamina.staminaCurrent -= 1;
        }
    }

Here is how you can reason about it frame by frame as it runs:

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

You must find a way to get the information you need in order to reason about what the problem is.

2 Likes

lol you’re a legend

1 Like

Hi! I tried to simplify a little bit your code to help you find your bug.

Here it is :slight_smile: Hope it helps.

public Slider staminaBar;
 
    private int currentStamina;
    public static StaminaBar instance;
    private WaitForSeconds regenTick = new WaitForSeconds(0.1f);
    private Coroutine regen;
    public bool IsDepleted => currentStamina <= 0;
    public PlayerStatsSOBJ objStamina;

    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        currentStamina = objStamina.staminaCurrent;
        staminaBar.maxValue = objStamina.staminaCurrent;
        UpdateBarValue();
        InvokeRepeating(nameof(DepleteStaminaPassively), 1.0f, 1.0f);
    }
 
    public void Update()
    {
        if (currentStamina >= 1 && IsDepleted)
        {
            //Not sure what you are trying to achieve.
            //(objStamina.staminaCurrent / objStamina.staminaCurrent will always be 1.)
            currentStamina += objStamina.staminaCurrent / objStamina.staminaCurrent;
            UpdateBarValue();
            RegenerateStamina();
        }
    }

    public void UserStamina(int amount)
    {
        var subtractionIsPositive = currentStamina - amount < 0;
        if (subtractionIsPositive || IsDepleted) return;
      
        currentStamina -= amount;
        UpdateBarValue();
        RegenerateStamina();
    }

    private void RegenerateStamina()
    {
        if (regen == null) regen = StartCoroutine(RegenStamina());
    }

    private void UpdateBarValue()
    {
        staminaBar.value = currentStamina;
    }

    private IEnumerator RegenStamina()
    {
        yield return new WaitForSeconds(2);
        while(currentStamina < objStamina.staminaCurrent && IsDepleted == false)
        {
            //Not sure what you are trying to achieve.
            //(objStamina.staminaCurrent / objStamina.staminaCurrent will always be 1.)
            currentStamina += objStamina.staminaCurrent / objStamina.staminaCurrent;
            UpdateBarValue();
            yield return regenTick;
        }
        if (currentStamina <= 0)
        {
            Debug.Log("Stamina Depleated");
            yield return new WaitForSeconds(2);
            while (currentStamina < objStamina.staminaCurrent && IsDepleted)
            {
                //Not sure what you are trying to achieve.
                //(objStamina.staminaCurrent / objStamina.staminaCurrent will always be 1.)
                currentStamina += objStamina.staminaCurrent / objStamina.staminaCurrent;
                UpdateBarValue();
                yield return regenTick;
            }
        }
        regen = null;
    }

    private void DepleteStaminaPassively()
    {
        if (currentStamina > 10)
        {
            staminaBar.value -= 1;
            objStamina.staminaCurrent -= 1;
        }
    }
1 Like

this actually helped a lot thankyou i didn’t realize how messy my code was that made things so much easier thankyou again

1 Like

Just a little bit of refactor, remove duplication of your code it could actually help a lot while debugging. Please let me know if you find the bug :stuck_out_tongue:

i did find the problem restructuring it helped me see that i got myself confused by having objStamina.staminaCurrent and currentStamina as 2 diffrent ints or at least i think thats what i got wrong by adding currentSamina to the function passiveStaminaDepleation() it fixed the problem. probably wouldn’t have copped the problem if i didnt restructure it despite reading over the code 25 times and a debug in every place i could put it haha thanyou for the help

1 Like