Most tutorials and other resources only cover very basic serialization. Like a single String, or a list of Ints with a BinaryFormatter. But I’d like some help with how to deal with more complicated situations.
Below is a simplified example of my code, where I want to serialize List worldTiles:
// Singleton
public class ShopLayout
{
public GameObject worldTile; // Prefab
public List<WorldTile> worldTiles = new List<WorldTile>();
}
// Represents a single tile in the world grid
public class WorldTile : MonoBehaviour
{
public Vector2 coordinates = new Vector2(); // x & y position of this tile in grid.
public PopulatedWorldObject populatedWorldObject;
}
// Some WorldObjects like chests and shelves also contain Items.
// It made sense to make WorldObject & Item children of same parent.
// But storedItems could be moved to WorldObject, and this class removed.
public class PopulatedWorldObject : MonoBehaviour
{
public WorldObject worldObject; // Sprite is populated in Inspector
public List<Item> storedItems = new List<Item>();
}
// Can be anything placed in the world. A rock, wall, door, chest, shelf.
public class WorldObject // Populated from list of WorldObjects in a ScriptableObject asset
{
public int ID; // Unique identifier
public string title; // Name of the Object
public Sprite sprite; // Sprite
}
// Items that the player can add to inventory or use.
// Some items come from a WorldObject.
public abstract class Item
{
public string slug; // Unique Identifier
public string title; // Name of item
public Sprite sprite; // Sprite
public float durability; // While the other properties will not change ever, durability will decrease
}
// Several classes derive from Item, such as; Weapons, Armor, Food, etc
public class Weapon : Item // Populated from list of Items in a ScriptableObject asset
{
public float damage;
}
Some issues I have with this:
- Should BinaryFormatter be used for cases like this, or are there better options?
- Is it recommended to serialize a list of custom class, containing a custom class, containing a list of a custom class? It seems like polymorphism hell.
- Sprite can’t (and probably shouldn’t) be serialized. How to handle that? Do I mark Sprite as [NonSerialized], and then when I deserialize, I use the unique identifier (ID or slug) to Resources.Load the Sprite? But everyone seems to advice against Resources.Load and GameObject.Find.
- Do I really need to serialize WorldObject & Item? Should I create a reference to the ScriptableObject? But how then to handle durability?
- How to smoothly handle instantiating of prefabs and populating them with deserialized data / classes, setting parents etc?
I think I could manage to write some working code, but since Unity is fairly new to me, I learn so much from tutorials and posts.
If someone could point me to some good resources (such as this), or has some advice to push me in the right directions, it would be very appreciated.