Search Unity

Question Best Practices for Serialization?

Discussion in 'Scripting' started by JudahMantell, Aug 14, 2021.

  1. JudahMantell

    JudahMantell

    Joined:
    Feb 28, 2017
    Posts:
    476
    So I have a quick question, and this might spawn a discussion:

    I am serializing parts of my scene using Json.
    For example, I have a monoBehavior called "Hero" which has things like int health, float speed, etc.

    When saving this data I am putting it into a HeroData class, then serializing that class. The HeroData class is basically only touched when saving and loading.

    Would it be more efficient to have a reference to a HeroData class per "hero" and use the data class when I need to access its variables? Then save that as is, cutting out the middleman?

    Or is it bad practice to use it for runtime operations (needed in Update, other scripts, etc)?

    Thanks!
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    It's common to have a secondary object related to the primary object used exclusively for saving and loading. It's a design pattern called a serialization surrogate or serialization proxy. The advantage of such a surrogate is that it allows you to transform the data when saving and loading: Imagine you have a list of allies saved as List<Character> in your Hero class, but you can't serialize Unity components, so you need to save your allies in the format of List<GUID> to re-build the references on load. I personally wouldn't use your object's save data in the functionality of the object for that very reason.
     
  3. JudahMantell

    JudahMantell

    Joined:
    Feb 28, 2017
    Posts:
    476
    Got it, thanks for the reply! That definitely clears things up!