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 SmallTimer · Mar 12, 2017 at 02:58 PM · c#saveloadnull reference exceptioncustom class

Save load custom class values not assigned object null reference

Okay, so in short, this is my first time trying to create save file codes and custom classes in unity, and the guides I am following does not provide all the data I need to figure out how to continue.

What I am trying to do is to, simply put, press a gui button, and that should set some variables from a custom script to a hard-coded value (this is just for testing, the values are meant to be some form of user input, either buttons or a text field) and save these values. Now, when I press my gui button, I get the error "reference Null Reference Exception: Object reference not set to an instance of an object".

I am probably doing a whole world of hurt with errors I cannot see here but this is the lines of code that unity points out as problems:

DemographicData.Completed.TD.Age = 20; DemographicData.Completed.TD.Gender = "Kvinde"; DemographicData.Completed.TD.AlreadyCompletedThis = true;

If I outcomment those three lines, unity stop complaining.

And this is the relevant code pieces:

Custom class script 1)

 using UnityEngine;
 using System.Collections;

 [System.Serializable]
 public class TestData{

     public bool AlreadyCompletedThis;
     public int Age;
     public string Gender;

     public TestData(){
         this.Age = 0;
         this.Gender = "";
         this.AlreadyCompletedThis = false;
     }
 }

Custom class 2

 [System.Serializable]
 public class DemographicData{
     public static DemographicData Completed;
     public TestData TD;
     public DemographicData(){
         TD = new TestData ();
     }
 }

The relevant code from the GUI script

 if (GUI.Button (new Rect ((Screen.width * 0.5f) - (SWdNoB * 3f * 0.5f), (Screen.height * 0.5f), SWdNoB * 3f, BoxHeight), "I'm filling out data")) {
     DemographicData.Completed.TD.Age = 20;
     DemographicData.Completed.TD.Gender = "Male";
     DemographicData.Completed.TD.AlreadyCompletedThis = true;
     SaveLoad.SaveTestData ();
     ContinueOnToMenu = true;
 }

The not so relevant save script, but just in case something is wrong here

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using System.Runtime.Serialization.Formatters.Binary;
 using System.IO;

 public static class SaveLoad {

     public static List<DemographicData> GameTestData = new List<DemographicData>();
     public static void SaveTestData(){
         SaveLoad.GameTestData.Add (DemographicData.Completed);
         BinaryFormatter bf = new BinaryFormatter ();
         FileStream file = File.Create (Application.persistentDataPath + "/GameTestData.gd");
         bf.Serialize (file, SaveLoad.GameTestData);
         file.Close ();
     }
     public static void LoadTestData (){
         if (File.Exists (Application.persistentDataPath + "/GameTestData.gd")) {
             BinaryFormatter bf = new BinaryFormatter ();
             FileStream file = File.Open (Application.persistentDataPath + "/GameTestData", FileMode.Open);
             SaveLoad.GameTestData = (List<DemographicData>)bf.Deserialize (file);
             file.Close ();
     }
 }

}

If it matters anything, The custom class "DemographicDate" is placed in the SaveLoad script, although it has been placed outisde everything.

I hope this is enough information to get the help I need, I normally love to figure these things out for myself, but I am lacking the time to do so.

Thanks in advance :)

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

1 Reply

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

Answer by SmallTimer · Mar 14, 2017 at 04:36 PM

So I foudn out that I called my list before I created it, and that I did not create the lists I though I was creating.

I solved the problem by putting a statement into the load function telling it that if there were no list, then create one, and in the gui script, I called the load function before trying to stuff things into it.

If someone somehow get the same error, this is my now changed code:

Custom class 1

(the same)

custom class 2

 [System.Serializable]
 public class DemographicData{
     *(deleted line)*
     public TestData TD;
     public DemographicData(){
         TD = new TestData ();
     }
 }

Gui script code

 void OnGUI () {

     /*(...)*/

         if (!StartWasPressed) {
             if (GUI.Button (new Rect (/*...*/), "Start")) {
                 SaveLoad.LoadTestData (); /*(This is where I make a list if there is none)*/
                 StartWasPressed = true;
             }
         }
         if (StartWasPressed) {
             ContinueOnToMenu = SaveLoad.GameTestData [0].TD.AlreadyCompletedThis;
             if (GUI.Button (new Rect (...), "Quit")) {
                 Application.Quit ();
             }
             if (!ContinueOnToMenu) {

                 if (DemographicsDataFilledOut [0]) { //age, gender, occupation
                     //age
                     GUI.Box(new Rect(/*...*/), "Please select your \n age range");
                     if (GUI.Button(new Rect(...)," - 15")){
                         /*(...)*/
                         SaveLoad.GameTestData [0].TD.Age = 1;
                         DataFieldMarkedCorrectly [0] = true;
                     }

                     /*(...)*/

                     if (GUI.Button (new Rect (/*...*/),"Continue")) {
                         if (/*all data filled out == true*/) {
                             SaveLoad.SaveTestData ();
                             DemographicsDataFilledOut [0] = false;
                             DemographicsDataFilledOut [1] = true;
                         }
                     }

                     /*(...)*/
                 }
                 /*(...)*/
             }

and the now very relevant save load script

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic; //This allows for dynamic lists
 using System.Runtime.Serialization.Formatters.Binary;
 using System.IO;

 public static class SaveLoad {

     public static List<DemographicData> GameTestData = new List<DemographicData>();
     public static void SaveTestData(){
         BinaryFormatter bf = new BinaryFormatter ();
         FileStream file = File.Create (Application.persistentDataPath + "/GameTestData.gd");
         bf.Serialize (file, SaveLoad.GameTestData);
         file.Close ();
     }
     public static void LoadTestData (){
         if (File.Exists (Application.persistentDataPath + "/GameTestData.gd")) {
             BinaryFormatter bf = new BinaryFormatter ();
             FileStream file = File.Open (Application.persistentDataPath + "/GameTestData.gd", FileMode.Open);
             SaveLoad.GameTestData = (List<DemographicData>)bf.Deserialize (file);
             file.Close ();
         } else { /*(This is where I make sure that a new list is created upon load call)*/
             SaveLoad.GameTestData.Add (new DemographicData());
         }
     }

Hopes this helps someone in the future.

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

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

6 People are following this question.

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

How can I get functionality similar to OnValidate for a custom class? 4 Answers

Making a bubble level (not a game but work tool) 1 Answer

Object reference is NULL when IT IS set to an instance of an object? 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