Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by FallingRocketGames · Oct 31, 2017 at 12:36 AM · c#error messagenullreferenceexception

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?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

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


}

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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.

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image FallingRocketGames · Oct 31, 2017 at 12:50 AM 0
Share

nope, same result, still pointing to this lines: CarAccel(); and chargerLevel = carScript.charger.currentLevel;

avatar image Bunny83 FallingRocketGames · Oct 31, 2017 at 01:24 AM 1
Share

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.

avatar image FallingRocketGames · Oct 31, 2017 at 12:52 AM 0
Share

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

avatar image MacDx FallingRocketGames · Oct 31, 2017 at 01:14 AM 0
Share

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.

Singletons

singletons.jpg (128.4 kB)
avatar image FallingRocketGames MacDx · Oct 31, 2017 at 01:20 AM 0
Share

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????

alt text

carro1.jpg (67.1 kB)

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

415 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges