首页 > 解决方案 > How to constantly update stamina system

问题描述

I'm trying to make a stamina system where if the player holds Shift they lose stamina.

I have it where every time Shift is pressed they lose some but how do I make them constantly lose stamina?

For instance every second they lose 3 instead of only losing 3 on the key press.

Here's the current code I have for it.

     //running
    if (Input.GetKeyDown(KeyCode.LeftShift))
    {
        speed = speed + run_speed;
        Stamina = Stamina - 3;
    }
    if (Input.GetKeyUp(KeyCode.LeftShift))
    {
        speed = speed - run_speed;
        Stamina = Stamina + 3;
    }

标签: c#unity3d

解决方案


Based on your code you can declare a boolean bool isRunning on the class and have it set to true when you run.

if (Input.GetKeyDown(KeyCode.LeftShift))
{
    speed = speed + run_speed;
    // Stamina = Stamina - 3;
    isRunning = true;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
    speed = speed - run_speed;
    // Stamina = Stamina + 3;
    isRunning = false;
}

Add this to your update function

private void Update(){
    if (isRunning) { Stamina -= 3 * Time.deltaTime }
    else { Stamina += 3 * Time.deltaTime }
}

推荐阅读