- Home /
 
Null Reference When Setting a Class?
Hi, I wrote a script to make a new CurrentFileData class and set it to the fileSerializer instance, but I'm getting a null reference on the line where I set saveData to newFileData. I tried making instances and even a "setter" function inside the Serializer class, but the SaveShipFile still returns errors.
 function SaveShipFile(v : ShipController)
 {
     var newFileData : CurrentFileData = new CurrentFileData();
     newFileData.ships = new List.<ShipController>();
     var j : ShipController = v;
         //sometimes this line gives an error
     newFileData.ships.Add(j);
     
         //this is the offending line
     fileSerializer.saveData = newFileData;
     fileSerializer.Save(Path.Combine(mdPath + "/Ships", "ShipTest.xml"));
 }
 
 
 @XmlRoot("SavedData")
 public class CurrentFileData {
     
     @XmlArray("Ships")
     @XmlArrayItem("Ship")
     public var ships : List.<ShipController> = new List.<ShipController>();
     
     
 }
 
 
 public class Serializer {
     
     public var saveData : CurrentFileData;
     
     public function Save(path : String)
      {
          var serializer : XmlSerializer = new XmlSerializer(CurrentFileData);
          var stream : Stream = new FileStream(path, FileMode.Create);
          serializer.Serialize(stream, saveData);
          stream.Close();
      }
  
      public static function Load(path : String):CurrentFileData
      {
          var serializer : XmlSerializer = new XmlSerializer(CurrentFileData);
          var stream : Stream = new FileStream(path, FileMode.Open);
          var result : CurrentFileData = serializer.Deserialize(stream) as CurrentFileData;
          stream.Close();
          return result;
      }
 
          public static function LoadFromText(text : String):CurrentFileData
          {
          var serializer : XmlSerializer = new XmlSerializer(CurrentFileData);
          return serializer.Deserialize(new StringReader(text)) as CurrentFileData;
      }
  }
 
               Thanks, any ideas would be appreciated!
Do you mean Line 10?
If yes, do you have something like fileSerializer = new Serializer() in your code?
Answer by SomeGuy22 · Jan 19, 2016 at 05:25 PM
@daleth90 was correct. I missed something so simple as not initializing fileSerializer...
However, it gave another error once that was cleared up. It said it could not implement GameObject.Transform as a serializable attribute, yet none of my classes derived from Monobehaviour. Turns out, just having a List of MonoBehaviours (ShipController) in CurrentFileData was enough to throw it off.
It'll be more complicated now that I have to extract specific data from a MonoBehaviour, but it works.
Your answer