[C#] [XNA] How can I correctly serialize this barrier class?

Started by
2 comments, last by chlerub 13 years, 11 months ago
When saving my level data I am currently saving an array of tiles. The tile class looks like the following:

    public class Tile3D
    {     
        public Barrier[] barriers;
        public Vector3 position;
        public float size;       
        public Tile3D_Type type;
        
        public Tile3D()
        {
            barriers = new Barrier[6];
        }
    }


The problem arises when I come to serialize/deserialize the barrier class. The barrier can be created from a quadrangle as follows:

    public class Barrier : IOctree_Object, IGUI_Object
    {
        RigidBody3D body;      
        Quadrangle quadrangle;
        Vector3 scale;
        List<CD_Triangle> triangles;

        public Barrier(Quadrangle quad)
        {
            quadrangle = quad;

            Vector3 s = new Vector3();
            s.X = quadrangle.Width;
            s.Y = quadrangle.Height;
            s.Z = 0;

            scale = s;
            triangles = new List<CD_Triangle>(quadrangle.Triangles);

            body = new RigidBody3D(quadrangle.Position, RigidBody3D_Type.Static);
            body.Shapes.AddRange(quadrangle.Triangles);

            Game1.Instance.physics3D.AddBody(this);
        }


The quadrangle class serializes with no problems but because the Barrier class requires a Quadrangle to be created properly, it can't be deserialized due to it not having a parameterless constructor. How can I serialize/deserialize the barrier class correctly knowing that I must have a parameterless constructor, and that I can create the barrier from a quadrangle?
Advertisement
Implement ISerializable?
Is that compatible with XML and XBOX 360?
Quick solution would be:

Mark the quadrangle field as public and add a parameterless ctor
Additionally i'd suggest to move all the logic code into an Init() method and out of the ctors.
It's tempting to use ctors beyond initializing fields and properties, but in the long run it turns out to be quite messy. At least from my experience.

This topic is closed to new replies.

Advertisement