Search code examples
c#serializationreferencexna-4.0

Storing references in serializable classes (C# - XNA)


I've been creating a game in XNA for the past couple weeks. In the process, I tried to solve a problem before I encountered it without fully understanding the problem.

That problem was how I was going to deal with saving and retrieving "blueprint" objects. I need this functionality due to a content creator that I'm making (the game is content-based). So the objective is, I create the content (rough example, an enemy of type "Goblin" with 100 health and a goblin sprite), save it to a serialized object, load it in the game, and then it is usable and duplicable in-game.

Now obviously when objects have something non-serializable like a Texture2D (the sprite), you can't serialize them. I solved that problem for both maps and objects with sprites (items, NPCs, characters, etc) by adding all my textures to a static class and only storing indices to the textures in the objects (e.g., instead of containing a Texture2D property, the Goblin would contain an index linking to the appropriate texture - slightly oversimplified but you get the idea).

But then the virus spread and I started doing that for all my object references. For example, the Goblin also needs a reference to an AI object. That AI object only has methods and as a result is clearly serializable, but I was storing it in the same static class as my textures and linking to it via index. Looking back on that now, I shudder as to what I was thinking.

So my question is, should everything except textures be stored by direct reference in serializable classes, instead of reference by index? Or is there ever a viable reason to do what I've done?

Serialization is a tricky business and I'm trying to wrap my head around the best ways to use it and the right times to avoid it.


Solution

  • As you said, serialization cannot keep track of references. Either you serialize the whole object graph, or you come up with your own way of resolving references upon deserializing. So what you did was the right thing to do, although you might want to find a better solution instead of just hanging everything from a static class.

    Also, you might want to change your strategy. Instead of saving the object itself with all the indices, you could save only the required information, and then have a resolver factory that would read this info and populate an object with the right values.