- Home /
sprint and stamina problems
soooo im having problems with my sprint and stamina function in my game i get an error saying
NullReferenceException: Object reference not set to an instance of an object Sprinter.SetRunning (Boolean isRunning) (at Assets/Scripts/Sprinter.cs:28) Sprinter.Update () (at Assets/Scripts/Sprinter.cs:36)
when i double click it, it highlights line 28 which is: cm.movement.maxForwardSpeed = isRunning ? runSpeed : walkSpeed;
and my code is:
using UnityEngine;
using System.Collections;
public class Sprinter : MonoBehaviour {
float stamina = 5, maxStanina = 5;
float walkSpeed, runSpeed;
CharacterMotor cm;
bool isRunning;
Rect staminaRect;
Texture2D staminaTexture;
void Start () {
cm = gameObject.GetComponent<CharacterMotor> ();
walkSpeed = cm.movement.maxForwardSpeed;
runSpeed = walkSpeed * 3;
staminaRect = new Rect (Screen.width / 10, Screen.height * 9 / 10,
Screen.width / 3, Screen.height / 50);
staminaTexture = new Texture2D(1, 1);
staminaTexture.SetPixel (0, 0, Color.white);
staminaTexture.Apply ();
}
void SetRunning(bool isRunning)
{
this.isRunning = isRunning;
cm.movement.maxForwardSpeed = isRunning ? runSpeed : walkSpeed;
}
void Update () {
if (Input.GetKeyDown( KeyCode.LeftShift))
SetRunning(true);
if (Input.GetKeyUp( KeyCode.LeftShift))
SetRunning(false);
if (isRunning)
{
stamina-=Time.deltaTime;
if (stamina < 0)
{
stamina = 0;
SetRunning(false);
}
}
else if(stamina<maxStanina)
{
stamina += Time.deltaTime;
}
}
void onGUI()
{
float ratio = stamina / maxStanina;
float rectWidth = ratio*Screen.width / 3;
staminaRect.width = rectWidth;
GUI.DrawTexture (staminaRect, staminaTexture);
}
}
someone please help its for a school assignment.
Thanks
So, if this line:
cm.movement.maxForwardSpeed = isRunning ? runSpeed : walkSpeed;
throws a nullreference, it's one out of two things: 1: cm is null 2: cm.movement is null
That's easy to check, just throw in some debugs above the line throwing the error:
Debug.Log(cm);
Debug.Log(cm.movement);
cm.movement.maxForwardSpeed = isRunning ? runSpeed : walkSpeed;
That'll get you closer.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
whats causing this error? 1 Answer
Javascript GUI and deathscript weird compiler errors 1 Answer
Joystick issues 2 Answers
Why is my terrain all grey? 1 Answer