- Home /
NullReferenceException, still the code is working?
Hi there I'm getting this error:
NullReferenceException: Object reference not set to an instance of an object PlayerStatus.CarAccel () PlayerStatus.Update ()
Apparently my script is not finding another script component but everything works fine, can't really say what's happening here any help will be appreciated!!
public class PlayerStatus : MonoBehaviour {
public static PlayerStatus playerStats;
[SerializeField] public CarSelector carScript;
[SerializeField] private int chargerLevel;
[SerializeField] private int corvetteLevel;
[SerializeField] private int shelbyLevel;
[SerializeField] private int upgradeLevel = 1;
[SerializeField] private int upgradeModifier = 1;
[SerializeField] private int defaultAccel;
[SerializeField] private int modAccel;
[SerializeField] private int currentCar;
private void Awake()
{
if (playerStats == null)
{
DontDestroyOnLoad(gameObject);
playerStats = this;
} else if (playerStats == this){ Destroy(gameObject); }
if (GetComponent<CarSelector>() != null) { carScript = carScript.GetComponent<CarSelector>(); }
else { Debug.LogWarning("Missing script"); }
}
// Update is called once per frame
void Update () {
CurrentVehicle();
CarAccel();
}
int CurrentVehicle()
{
currentCar = carScript.seleccionPositiva;
return currentCar;
}
int CarAccel()
{
switch (CurrentVehicle()) {
case 0:
chargerLevel = carScript.charger.currentLevel;
switch (chargerLevel)
{
case 1:
modAccel = carScript.corvette.accel * 1;
lvl1();
break;
case 2:
modAccel = carScript.corvette.accel * 3;
lvl2();
break;
case 3:
modAccel = carScript.corvette.accel * 5;
lvl3();
break;
}
break;
I do get the car model and the acceleration even the modified acceleration but I get this error whenever I compile the script, sometimes points to CarAccel(); and I do get the Missing script warning, what I'm I doing wrong here?
Answer by FallingRocketGames · Nov 09, 2017 at 11:22 PM
The solution came after changing the approach to the code, for some reason unity wasn't detecting my script not even after adding the script like this...
carScriptGO = GameObject.Find("CarSelector");
carScript = carScriptGO.GetComponent<CarSelector>();
carScript.enabled = true;
last instruction had to be added because I noticed again for some reason unity disabled the script game object.
CarSelector had the information for each car let's say the model name, the acceleration, weight and all sort of things, that's why I had to pull the information of each car from that script in this way:
chargerLevel = carScript.charger.currentLevel;
Which actually did work!!! but gave me this Null reference exception error each time I hit "play", so my best option was to put the car values in the same script I'm using as a Hashtable ending in something like this...
public class PlayerStatus : MonoBehaviour {
public GameObject carScriptGO;
public CarSelector carScript;
public Hashtable carCharger = new Hashtable();
[SerializeField] private int upgradeLevel = 1;
[SerializeField] private int upgradeModifier = 1;
[SerializeField] private GameObject lvl2Lock;
[SerializeField] private GameObject lvl3Lock;
[SerializeField] private GameObject lvl2Bar;
[SerializeField] private GameObject lvl3Bar;
[SerializeField] private int availableCoins;
[SerializeField] private Text availableCoinsTxt;
[SerializeField] private int costInCoins;
[SerializeField] private Text neededCoinsTxt;
[SerializeField] private Image accelBar;
[SerializeField] private float[] modAccel = new float[12];
[SerializeField] private int currentCar; //selector del Carro
private void Awake()
{
carScriptGO = GameObject.Find("CarSelector");
carScript = carScriptGO.GetComponent<CarSelector>();
carScript.enabled = true;
this.gameObject.GetComponent<PlayerStatus>().enabled = true;
LoadCars();
}
// Use this for initialization
void Start () {
if (GetComponent<CarSelector>() == null) { Debug.LogWarning("Missing script"); }
costInCoins = 0;
availableCoins = 0;
}
// Update is called once per frame
void Update () {
CurrentVehicle();
CarAccel();
}
int CurrentVehicle()
{
currentCar = carScript.seleccionPositiva;
return currentCar;
}
void CarAccel()
{
switch (CurrentVehicle()) {
case 0: //CHARGER
int chargerLevel = (int)carCharger["currentlevel"];
switch (chargerLevel)
{
case 1:
modAccel[CurrentVehicle()] = (int)carCharger["accel"] * 1;
costInCoins = (int)carCharger["lvlTwoPrice"];
print(costInCoins);
lvl1();
break;
case 2:
AccelBar();
modAccel[CurrentVehicle()] = (int)carCharger["accel"] * 3;
costInCoins = (int)carCharger["lvlThreePrice"];
print(costInCoins);
lvl2();
break;
case 3:
modAccel[CurrentVehicle()] = (int)carCharger["accel"] * 5;
lvl3();
break;
}
print("Acceleration for " + (string)carCharger["model"] + " modified is: " + modAccel[CurrentVehicle()]);
break;
}
}
void lvl1()
{
}
void lvl2()
{
}
void lvl3()
{
}
//CAR LOADERS
void LoadCars() {
LoadCharger();
}
void LoadCharger()
{
carCharger.Add("model", "Dodge Charger");
carCharger.Add("accel", 16);
carCharger.Add("weight", 100);
carCharger.Add("currentlevel", 2);
carCharger.Add("lvlTwoPrice", 58);
carCharger.Add("lvlThreePrice", 180);
}
}
Answer by Bunny83 · Oct 31, 2017 at 12:43 AM
This line makes no sense:
else if (playerStats == this){ Destroy(gameObject); }
You most likely want to destroy any duplicates of this object which is not the stored static reference. So it should read:
else if (playerStats != this){ Destroy(gameObject); }
Next thing is this line:
carScript = carScript.GetComponent<CarSelector>();
You can't call GetComponent of "carScript" since that's the one variable you try to initialize. It probably should be:
carScript = GetComponent<CarSelector>();
There may be other errors but nothing in the code that we see.
nope, same result, still pointing to this lines: CarAccel(); and chargerLevel = carScript.charger.currentLevel;
You have never said the error points to this line:
chargerLevel = carScript.charger.currentLevel;
Why didn't you copy the stacktrace of the error from the console?
Anyways if you get a NullReference exception on this line there are only two possible reasons:
Either "carScript" is null
or "charger" is null
If carScript is null that means there is no "CarSelector" script on the same gameobject. If you actually want to assign an externally located CarSelector script manually in the inspector you should remove the GetComponent line completely Either assign the reference in the inspector or assign in via code using GetComponent.
If "charger" is null we can't really help you any further since we don't know anything about your "CarSelector" class, what that "charger" variable or property contains and how it's initialized.
I mean is not that the code is not working but I can't get rid of the error I'm afraid this might be a problem if I try to compile the whole enchilada later
I'm pretty sure your problem has to do something with how you are trying to make this class share all it's information with other objects ($$anonymous$$aking it a singleton). The thing that I find the weirdest is that you say you get the error every time you try to compile the script however, the error call stack you posted says the error comes from CarAccel() which comes from Update() and how is that possible at compile time is above me.
Remember that static variables are never garbage collected, a static field on a mono script or any other class will live until you close the unity editor or the app itself if it is a built game. I may be wrong but my theory is that even if you call destroy on the gameobject that contains this script, the static playerStats field is making it stay alive somehow and that may be interfering with Unity's compilation/serialization process.
Not exactly I'm sorry lack of communication here, I get the error when I hit play and yes I also assume the problem is the "singleton" I'm trying to create, is just that I need to save the information from this script to the next scenes so you play with the selected car and also for the player to preserve the level of his car, should I let it be and just worry when I build the app????
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Attach script twice. 1 Answer
NullReferenceException 1 Answer
NullReferenceException: Object reference not set to an instance of an object. (Cameras switching) 1 Answer