using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using UnityEditor; using UnityEngine; using NaughtyAttributes; [ExecuteAlways] public class InspectorSetter : MonoBehaviour { // the gap of data is on quit in the editor // on quit -> save to file and queue editor setter public CustomDic[] customDic = new CustomDic[1024]; public string filePath = "C:/dofdev/SnakeInABox/Assets/Data.dat"; [Header("References")] public Monolith mono; public Remember remember; [Button] public void FreshDic() { customDic = new CustomDic[1024]; File.Delete(filePath); } public void Queue() { Serialize(); remember.queued = true; EditorUtility.SetDirty(remember); } public void Update() { if (remember.queued) { if (File.Exists(filePath)) { Deserialize(); mono.Fetch(this); remember.queued = false; EditorUtility.SetDirty(mono); EditorUtility.SetDirty(remember); } } } public void Serialize() { FileStream fs = new FileStream(filePath, FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(fs, customDic); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Close(); } } public void Deserialize() { FileStream fs = new FileStream(filePath, FileMode.Open); try { BinaryFormatter formatter = new BinaryFormatter(); customDic = (CustomDic[])formatter.Deserialize(fs); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { fs.Close(); } } public void Set(string key, dynamic data) { for (int i = 0; i < customDic.Length; i++) { if (customDic[i].key == key) { if (data.GetType() == typeof(Vector3) || data.GetType() == typeof(Vector3Int)) { customDic[i + 0].data = data.x; customDic[i + 1].data = data.y; customDic[i + 2].data = data.z; } else { customDic[i].data = data; } break; } else if (customDic[i].key == "") { if (data.GetType() == typeof(Vector3) || data.GetType() == typeof(Vector3Int)) { customDic[i + 0] = new CustomDic(key, data.x); customDic[i + 1] = new CustomDic(key, data.y); customDic[i + 2] = new CustomDic(key, data.z); } else { customDic[i] = new CustomDic(key, data); } break; } } } public dynamic Fetch(string key, dynamic data) { int i = 0; while (i < customDic.Length) { if (customDic[i].key == key) { if (data.GetType() == typeof(Vector3)) { return new Vector3(customDic[i + 0].data, customDic[i + 1].data, customDic[i + 2].data); } else if (data.GetType() == typeof(Vector3Int)) { return new Vector3Int(customDic[i + 0].data, customDic[i + 1].data, customDic[i + 2].data); } else { return customDic[i].data; } } else if (customDic[i].key == "") { break; } i++; } return data; } } [Serializable] public class CustomDic { public CustomDic(string key, dynamic data) { this.key = key; this.data = data; } public string key; public dynamic data; }