user164226
user164226

Reputation:

Persistent storage of object type identifiers

I've read that databases should primarily be used to store data that changes, and that business logic data should reside in the program executable.

If this is the case, how does one represent relations between runtime instances in a way that can be rehydrated in the next session?

Say I have a game in which the player has equipped a "Sword of a Thousand Truths". In C# I've described this as an instance of a type: var s = new SwordOf100Truths() and associated it with the player's inventory: pc.Equip("MainHand", s). Then the player saves the game and exits.

When that player logs back in, I need to know how to recreate their inventory.

Of course I could store records in SQL for every possible item type (GameObject.Equipment.Weapon.Sword.SwordOf100Truths, GameObject.Consumeable.Potion.HealthRank3...), and then have a PlayerInventories table which would get a new record keyed to that particular item id. Then when the player logs back in, I parse the type name and create an instance of it. But this seems awfully inefficient.

Or I could just store the object's type name in the inventory table and recreate it, without having to store all possible items.

Table PlayerInventories Id, PlayerId, TypeName, InventorySlot

foreach(item in GetPlayerInventoryData(playerId))
{
    pc.Equip(item.InventorySlot, Activator.CreateInstance(type.GetType(item.TypeName)));
}

Is this the way to go? How do folks generally deal with this?

Upvotes: 0

Views: 120

Answers (1)

dbugger
dbugger

Reputation: 16464

You are already thinking of the player as an object and its items as objects -- store them that way as well. No need to go relational. Store the whole player's object graph as a single entity. There are a number of tools and techniques to accomplish this. I've used BSON and JSON to represent the objects, and they lend themselves to easy serialization\deserialization and can be placed in any data store. JSON is nice if you are working with javascript on your front end as you can consume it directly.

This also means you can add objects at any time without having to redo your database, as long as you can serialize the object, you can save it and re-constitute it.

Upvotes: 1

Related Questions