While trying to save to a file a list of objects needed to run my game, I noticed that Texture2D is not serializable. Why? What was the purpose?

The object I want to serialize looks like this:

public class GameObject
    private Vector2 position_ = Vector2.Zero;
    private float rotation_ = 0.0f;
    private Vector2 scale_ = Vector2.One;
    private float depth_ = 0.0f;

    private Texture2D texture_;

    private bool is_passable_ = true;

    private GameObject(
        Vector2 starting_position,
        string filepath,
        ContentManager content)
        this.position_ = starting_position;
        this.texture_ = Content.Load<Texture2D>(filepath);


So, what should I serialized since Texture2D isn't made to be used that way?


You should serialize a reference to the texture (such as its file name), not the texture itself. That way when you load the serialized game object later, you know which texture to look up and associate with the object.

You don't want to serialize the entire texture with the object, because that would be a huge waste of space when objects started to share textures (when serialized, they'd each have a complete copy of the texture bytes). That's why the Texture2D object itself isn't marked as serializable. It's trying to protect you from yourself.

This is related to why it's generally a good idea to separate game logic state from rendering and visual presentation state.

  • \$\begingroup\$ One tip it to see the object constructor. You see that you only need the starting position and the filepath. \$\endgroup\$ Jan 2 '14 at 22:00
  • \$\begingroup\$ @GustavoMaciel Maciel Should I add a "filename" private field for every GameObject, serialize it and then while deserializing reload the texture using that filename? \$\endgroup\$
    – user31021
    Jan 3 '14 at 10:06
  • \$\begingroup\$ @JoshPetrie In this simple case, what does it mean "separate game logic state from..."? Does it mean that the texture shouldn't be inside my GameObject class? Can please give me a simple pattern to show that? \$\endgroup\$
    – user31021
    Jan 3 '14 at 10:10
  • 1
    \$\begingroup\$ At the basic level it means to keep anything directly render-related (like texture objects) out of your game logic classes. Have separate objects for rendering things, and at the top level of your game, facilitate the transfer of data between the two. It's a broad topic and you should be able to find many resources on such a separation of concerns by searching. \$\endgroup\$
    – user1430
    Jan 3 '14 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy