public void Flush() { foreach (var pair in m_Cache) { if (pair.Value == null) { continue; } var filePath = GetFilePathForKey(pair.Key); try { var directory = Path.GetDirectoryName(filePath); if (directory != null) { Directory.CreateDirectory(directory); var serializedData = StateComponentHelper.Serialize(pair.Value); File.WriteAllText(filePath, serializedData, Encoding.UTF8); } } catch (Exception e) { Debug.LogError($"Error saving file {filePath}. Error: {e}"); } } m_Cache.Clear(); }
public TComponent GetState <TComponent>(Hash128 key, Func <TComponent> defaultValueCreator = null) where TComponent : class, IStateComponent { ThrowIfInvalid(key); if (m_Cache.TryGetValue(key, out var vsc)) { return(vsc as TComponent); } TComponent obj = null; var filePath = GetFilePathForKey(key); if (File.Exists(filePath)) { string serializedData; try { serializedData = File.ReadAllText(filePath, Encoding.UTF8); } catch (Exception e) { Debug.LogError($"Error loading file {filePath}. Error: {e}"); serializedData = null; } if (serializedData != null) { try { obj = StateComponentHelper.Deserialize <TComponent>(serializedData); } catch (ArgumentException exception) { Debug.LogError($"Invalid file content for {filePath}. Removing file. Error: {exception}"); // Remove invalid content RemoveState(key); obj = null; } } } if (obj == null) { obj = defaultValueCreator?.Invoke(); } if (obj != null) { m_Cache[key] = obj; } return(obj); }