Griff1th

list and dict

May 4th, 2023
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | Gaming | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public static class JsonUtilityList
  6. {
  7.     public static List<T> FromJson<T>(string json)
  8.     {
  9.         Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
  10.         return wrapper.Items;
  11.     }
  12.    
  13.     public static string ToJson<T>(List<T> list, bool prettyPrint = false)
  14.     {
  15.         Wrapper<T> wrapper = new Wrapper<T>(list);
  16.         return JsonUtility.ToJson(wrapper, prettyPrint);
  17.     }
  18.  
  19.  
  20.     [Serializable]
  21.     private class Wrapper<T>
  22.     {
  23.         public List<T> Items;
  24.         public Wrapper(List<T> items)
  25.         {
  26.             Items = items;
  27.         }
  28.     }
  29. }
  30.  
  31. using UnityEngine;
  32. using System.Collections.Generic;
  33.  
  34. [System.Serializable]
  35. public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
  36. {
  37.     [SerializeField] private List<TKey> keys = new List<TKey>();
  38.     [SerializeField] private List<TValue> values = new List<TValue>();
  39.  
  40.    
  41.     public void OnBeforeSerialize()
  42.     {
  43.         keys.Clear();
  44.         values.Clear();
  45.         foreach (KeyValuePair<TKey, TValue> pair in this)
  46.         {
  47.             keys.Add(pair.Key);
  48.             values.Add(pair.Value);
  49.         }
  50.     }
  51.    
  52.     public void OnAfterDeserialize()
  53.     {
  54.         this.Clear();
  55.  
  56.         if (keys.Count != values.Count)        
  57.             Debug.LogError(" the amount of keys ("+ keys.Count + ") does not match the number of values (" + values.Count + ") so something went wrong");
  58.        
  59.         for (int i = 0; i < keys.Count; i++)        
  60.             this.Add(keys[i], values[i]);
  61.        
  62.     }
  63. }
  64.  
  65.  
  66.  
Advertisement
Add Comment
Please, Sign In to add comment