Quantcast
Channel: Questions in topic: "class instance"
Viewing all articles
Browse latest Browse all 131

Error while serializing and deserializing multiple instances of a class while saving and loading persistent data

$
0
0
This is the code that I had written to store the details of 4 toys with their id and their vector 3 positions. But there is some error that's giving me trouble, and I can't identify what that error is. > EndOfStreamException: Failed to read past end of stream. Can some one please tell me what the error is? I need to save the details of 4 game objects after they are placed in the game scene by the user. When the user place a game object in the game scene, the SaveToyPosition method is called by passing the id of the object placed and its transform.localPosition. Some times the player may or may not place all the 4 objects fully in the game scene as they are very costly items to be purchased by the user. Since vector3 cannot be serialized as such, I went for this method. Can some one please help. I'm new to serializing multiple instances of the same class to a file and then de-serializing it while loading it when played again. Thanks in advance. Please correct me if I did anything wrong in the code. function SaveToyPosition(id:int,Pos:Vector3) { var bf:BinaryFormatter=new BinaryFormatter(); var file:FileStream=File.Create(Application.persistentDataPath +"/BathroomToyInfo.dat"); var Toy1=new ToyData(); var Toy2=new ToyData(); var Toy3=new ToyData(); var Toy4=new ToyData(); if(id==1) { Toy1.id=id; Toy1.xpos=Pos.x; Toy1.ypos=Pos.y; Toy1.zpos=Pos.z; bf.Serialize(file,Toy1); } if(id==2) { Toy2.id=id; Toy2.xpos=Pos.x; Toy2.ypos=Pos.y; Toy2.zpos=Pos.z; bf.Serialize(file,Toy2); } if(id==3) { Toy3.id=id; Toy3.xpos=Pos.x; Toy3.ypos=Pos.y; Toy3.zpos=Pos.z; bf.Serialize(file,Toy3); } //Similarly Toy 4 is there file.Close(); } class ToyData extends System.Object { var id:int; var xpos:float; var ypos:float; var zpos:float; } function LoadToyPosition() { if(File.Exists(Application.persistentDataPath +"/BathroomToyInfo.dat")) { var bf:BinaryFormatter=new BinaryFormatter(); var file:FileStream=File.Open(Application.persistentDataPath +"/BathroomToyInfo.dat",FileMode.Open); var Toy1:ToyData=bf.Deserialize(file) as ToyData; var Toy2:ToyData=bf.Deserialize(file) as ToyData; toyid=Toy1.id; xpos=Toy1.xpos; ypos=Toy1.ypos; zpos=Toy1.zpos; toyid1=Toy2.id; xpos1=Toy2.xpos; ypos1=Toy2.ypos; zpos1=Toy2.zpos; //Similarly Toy 3 and Toy 4 is there Debug.Log("Toy ID "+Toy1.id+" Xpos "+xpos+" Ypos "+ypos+" Zpos "+zpos); Debug.Log("Toy ID "+Toy2.id+" Xpos "+xpos1+" Ypos "+ypos1+" Zpos "+zpos1); file.Close(); } }

Viewing all articles
Browse latest Browse all 131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>