sprinting GUI help

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;
		}
	}
}

copy the whole error code and paste it here. :slight_smile: if you haven’t fixed it yet.

NullReferenceException: Object reference not set to an instance of an object
StaminaBarGUI.updateStamina() (at Assets/Scripts/GUI 1/StaminaBarGUI.cs: 37)

The error says that you don’t have any Character Controller attached to the game object that has the StaminaBarGUI script.

so this charController = GetComponent<CharacterController>();

should be

charController = player.GetComponent<CharacterController>();

note that you should be able to access the player game object. :slight_smile: let me know if thats your problem.

CharController script is probably not attached to your GameObject.

yeah that was the reason, I accidentally attached the script to the wrong one.