I’m getting a null reference exception so I’m not sure what’s wrong with the code. I’m trying to update the stamina GUI, so that when holding the left shift and the movement keys the stamina GUI, will start to decrease.
Anyways, the null reference is happening on this line of code:
“if(charController.velocity.magnitude > 0 Input.GetKey(KeyCode.LeftShift))”
using UnityEngine;
using System.Collections;
public class StaminaBarGUI : MonoBehaviour
{
float maxStamina = 100;
float currentStamina = 100;
int barLength;
private CharacterMotor charMotor;
private CharacterController charController;
// Use this for initialization
void Start ()
{
barLength = Screen.width / 6;
charMotor = GetComponent<CharacterMotor>();
charController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update ()
{
updateStamina();
}
void OnGUI()
{
GUI.Box(new Rect(5, 30, 60, 20), "Stamina");
GUI.Box(new Rect(65, 30, barLength, 20), currentStamina.ToString("0"));
}
void updateStamina()
{
//decreases stamina bar when sprinting
if(charController.velocity.magnitude > 0 Input.GetKey(KeyCode.LeftShift))
{
currentStamina -= Time.deltaTime * 10;
}
//default speed, when not sprinting
else
{
charMotor.movement.maxForwardSpeed = 5;
charMotor.movement.maxSidewaysSpeed = 5;
}
//stamina regeneration
if(charController.velocity.magnitude == 0 (currentStamina >= 0))
{
currentStamina += Time.deltaTime * 5;
}
//run speed returns to normal (while sprinting), when stamina reeaches 0
if(charController.velocity.magnitude > 0 Input.GetKey(KeyCode.LeftShift)
currentStamina <= 0)
{
charMotor.movement.maxForwardSpeed = 5;
charMotor.movement.maxSidewaysSpeed = 5;
}
//stamina can't go above 100
if(currentStamina >= maxStamina)
{
currentStamina = maxStamina;
}
//stamina can't drop below 0
if(currentStamina <= 0)
{
currentStamina = 0;
}
}
}