Search Unity

Question Non-deterministic saving of Json data

Discussion in 'Visual Scripting' started by Rob-Fireproof, Apr 19, 2023.

  1. Rob-Fireproof

    Rob-Fireproof

    Joined:
    Dec 18, 2012
    Posts:
    56
    Hi there,

    Has anyone else had issues with the json data for the elements of an embedded graph in the Unity scene file being in a different order when the scene is saved? It's causing a bit of a pain for us in merging changes.

    I'm trawling through the serialization code to try to find a solutions. Just wondering if anyone else has come across this and if there's a workaround for it?

    Thanks!
    Rob.
     
  2. Rob-Fireproof

    Rob-Fireproof

    Joined:
    Dec 18, 2012
    Posts:
    56
    OK, I think it's down to the elements being sorted in the deserialization code by dependencyOrder, which is generally a low number shared by a lot of elements (i.e. loads of elements will be 0, loads are 1 etc.).

    I think a solution is to change the OnBeforeSerialize function in graph.cs to sort them into a consistent order. I've chosen to do it by dependency order and then by guid. i.e:


    Code (CSharp):
    1. public virtual void OnBeforeSerialize()
    2. {
    3.     _elements.Clear();
    4.  
    5.     var sortedElements = ListPool<IGraphElement>.New();
    6.     foreach (var element in elements)
    7.     {
    8.         sortedElements.Add(element);
    9.     }
    10.     sortedElements.Sort(CompareElements);
    11.  
    12.     _elements.AddRange(sortedElements);
    13. }
    14.  
    15. private static int CompareElements(IGraphElement a, IGraphElement b)
    16. {
    17.     int dependencyComparison = a.dependencyOrder.CompareTo(b.dependencyOrder);
    18.     return dependencyComparison != 0 ? dependencyComparison : a.guid.CompareTo(b.guid);
    19. }
    I need to give this a LOT of testing. If anyone can see a problem with it, please let me know!
    Rob.