Search Unity

Unity Design Pattern: Fastest Serialisation Example

Discussion in 'Community Learning & Teaching' started by disanity, Jul 7, 2017.

  1. disanity

    disanity

    Joined:
    Jul 7, 2017
    Posts:
    1
    In Part 1 of series: we use simple c# classes to create modular code. However none of them are serialisable.
    In Part 3 we find an approach to make them serialisable without increasing scene file size.

    Scene file size is important as it affects the loading time of the scene. Removing needless serialisation references optimizes our game speed.

    The problem with Part 1 is that ... Assembly reload wipes non serialisable classes. In part 1 we solved that with a crude hack on Enable. In part 3, we found the problem solution. All our troubles are gone. How? Simple. Private variables.

    private variables are not serialized in initial scene file (= 0 initial file size), but are serialized on assembly reload. This allows us to achieve the absolute optimization trick.

    Code (CSharp):
    1. namespace Disanity.Test
    2. {
    3.     using UnityEngine;
    4.     /// Conclusion: Private variables are not saved in initial scene but their values persist in Assembly Reload = Best of both worlds.
    5.     public class TestPrivateSerialisation : MonoBehaviour
    6.     {
    7.         private int a;
    8.         void Awake()
    9.         {
    10.             a = Util.RandomInt(312, 4145);
    11.         }
    12.         private void OnEnable()
    13.         {
    14.             Debug.Log("Generated Value "+a);
    15.         }
    16.     }
    17. }
    By running the following code we get :

    Output: 2942
    Output after reload: 2942

    Full Details and code: https://disanity.wordpress.com/2017/07/07/unity-private-variable-serialisation/