- Home /
Object reference not set to an instance of an object
I get this error whenever I press 5: NullReferenceException:
Object reference not set to an instance of an object WarriorSpin.Update () (at Assets/Scripts/SpellsAndAbilities/Warrior/WarriorSpin.cs:30)
I have checked to make sure everything is the way it is supposed to be but it still doesn't work.
Here is my code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class WarriorSpin : MonoBehaviour {
public GameObject player;
public float coolDown;
PlayerScript ps;
public GameObject canvas;
public GameObject errorMessageArea;
void Start () {
player = gameObject;
ps = player.GetComponent<PlayerScript> ();
canvas = GameObject.Find ("HudCanvas");
errorMessageArea = GameObject.Find ("ErrorMessageArea");
}
void Update () {
if (Input.GetButtonDown ("5")) {
if (coolDown <= 0) {
if (ps.mana > 50) {
ps.isWarriorSpin = true;
coolDown = 30;
ps.mana -= 50;
} else {
GameObject notEnoughManaObject = Instantiate (ps.notEnoughMana, errorMessageArea.transform.position, errorMessageArea.transform.rotation) as GameObject;
notEnoughManaObject.transform.SetParent (canvas.gameObject.transform);
}
} else {
GameObject notReadyYetObject = Instantiate (ps.notReadyYet, errorMessageArea.transform.position, errorMessageArea.transform.rotation) as GameObject;
notReadyYetObject.transform.SetParent (canvas.gameObject.transform);
}
}
if (GetComponent<Text> () != null && coolDown > 1) {
GetComponent<Text> ().text = "" + coolDown.ToString ("0");
}
if (GetComponent<Text> () != null && coolDown > 0 && coolDown <= 1) {
GetComponent<Text> ().text = "" + coolDown.ToString ("F1");
}
if (GetComponent<Text> () != null && coolDown <= 0) {
GetComponent<Text> ().text = "";
}
coolDown -= Time.deltaTime;
}
}
Answer by OncaLupe · Nov 01, 2015 at 05:18 PM
As long as the numbering matches up, the error is from the line if (ps.mana > 50) {
. This generally means the variable 'ps' has not been assigned an object to point to. The Start() method tries to set this on line 20, but you never confirm if it was successful. If the object set to the 'player' variable does not contain 'PlayerScript', then 'ps' will be null and give the error.
Also, it looks like you're Instantiating an error message object and attaching it to the UI Canvas. Instantiating is an expensive operation. It'd be much better to already have a generic error message display on the UI, and call a method on it to display whatever error comes up.
I tested if ps was set by making it public for a second and looked in the inspector. It said that ps was set to the PlayerScript of the gameobject. So ps is set and that's why I'm confused. If it is set then why is it giving me this error?
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Object reference not set to an instance of an object in c# class. 1 Answer
Multiple Cars not working 1 Answer
Particle circle HELP 1 Answer
Internal Compiler Error - Lidgren 0 Answers