I'have this problem. (sorry for the links but I'm not allowed to insert images yet). I would like to serialize the position, rotation, name and current scene of a gameObject. But only the object name of the current scene (strings) works fine, not the position data (Vector3 type) and rotation (Quaternion type). This is the class to be serialized, very simple:
[Serializable]
public class SpaceObjectData
{
[DataMember]
public string sObjectName;
[DataMember]
public Vector3 transformPosition;
[DataMember]
public Quaternion transformRotation;
[DataMember]
public string sceneLocation;
}
This is the code for serialize my class and and save it on file :
public void SetState()
{
// Stream the file with a File Stream. (Note that File.Create() 'Creates' or 'Overwrites' a file.)
FileStream file = File.Create(path);
//Serialize to xml
DataContractSerializer bf = new DataContractSerializer(ObjectData.GetType());
MemoryStream streamer = new MemoryStream();
//Serialize the file
bf.WriteObject(streamer, ObjectData);
streamer.Seek(0, SeekOrigin.Begin);
//Save to disk
file.Write(streamer.GetBuffer(), 0, streamer.GetBuffer().Length);
file.Close();
}
This is the saved file code:
everything seems OK This is the function to read the file and deserialize the stream:
public void GetState()
{
if (System.IO.File.Exists(path))
{
string text = System.IO.File.ReadAllText(path);
using (Stream stream = new MemoryStream())
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
stream.Position = 0;
DataContractSerializer serializer = new DataContractSerializer((ObjectData.GetType()));
ObjectData = (SpaceObjectData)serializer.ReadObject(stream);
}
print(ObjectData.sObjectName); //output OK
print(ObjectData.sceneLocation); //output OK
print(ObjectData.transformPosition); //output wrong (always 0,0,0)
print(ObjectData.transformRotation); //output wrong (always 0,0,0,0)
}
}
Where is that wrong? Why do not you read the Vector3 and Quaternion data? How should I save the Vector3 and Quaternions to be able to deserialize and read them?