Hello, I just recently started using unity and how to code in C# (like less than a day), I was wondering if anyone could help me with an issue I keep having where the stamina seems to drain too fast and I don’t know what seems to be causing it. And if you have any suggestions on how to improve on this please let me know
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement2 : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 10f;
public bool isSprinting = false;
public float crouchHeight = 3.4f;
public bool isCrouching = false;
public float standingHeight = 3.8f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
private int maxStam = 200;
private int currentStam;
private WaitForSeconds regenTick = new WaitForSeconds(1f);
private Coroutine regen;
Vector3 velocity;
bool isGrounded;
// Start is called before the first frame update
void Start()
{
currentStam = maxStam;
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y <0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
if(move.magnitude>1)
move/=move.magnitude;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
if(Input.GetKey(KeyCode.LeftShift))
{
isSprinting = true;
}
else
{
isSprinting = false;
}
if (isSprinting == true)
{
if (currentStam - 1 >=0)
{
currentStam -= 1;
speed = 18f;
if(regen != null)
{
StopCoroutine(regen);
}
regen = StartCoroutine(RegenStamina());
Debug.Log(currentStam);
}
else
{
Debug.Log("Not Enough Stam Fam!");
speed = 8f;
}
}
else
{
speed = 8f;
}
if(Input.GetKey(KeyCode.LeftControl))
{
isCrouching = true;
}
else
{
isCrouching = false;
}
if(isCrouching == true)
{
controller.height = crouchHeight;
speed = 3f;
}
else
{
controller.height = standingHeight;
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime * 2);
}
private IEnumerator RegenStamina()
{
yield return new WaitForSeconds(4);
while(currentStam < maxStam)
{
currentStam += maxStam / 100;
yield return regenTick;
Debug.Log(currentStam);
}
}
}