using System; using System.IO; using UnityEngine; public class FileUtil { public static (bool OK, string Message) SaveText(string fileName, string filePath, string content) { try { string fullPath = Path.Combine(filePath, fileName); string directory = Path.GetDirectoryName(fullPath); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); File.WriteAllText(fullPath, content); return (true, $"Файл успешно сохранен: {fullPath}"); } catch (Exception ex) { return (false, $"Ошибка сохранения: {ex.Message}"); } } public static (bool OK, string Message, string Content) LoadText(string fileName, string filePath) { try { string fullPath = Path.Combine(filePath, fileName); if (!File.Exists(fullPath)) { return (false, $"Файл не найден: {fullPath}", null); } string content = File.ReadAllText(fullPath); return (true, $"Файл успешно загружен: {fullPath}", content); } catch (Exception ex) { return (false, $"Ошибка загрузки: {ex.Message}", null); } } public static (bool OK, string Message) SaveJson(string fileName, string filePath, T data) { try { string json = JsonUtility.ToJson(data, true); return SaveText(fileName, filePath, json); } catch (Exception ex) { return (false, $"Ошибка сохранения JSON: {ex.Message}"); } } public static (bool OK, string Message) SaveJson(string fileName, AppDirectory directory, T data) => SaveJson(fileName, GetDirectoryName(directory), data); private static string GetDirectoryName(AppDirectory directory) { return directory switch { AppDirectory.Streaming => Application.streamingAssetsPath, AppDirectory.Persistent => Application.persistentDataPath, _ => Path.Combine(Application.persistentDataPath, "TRASH") }; } public static (bool OK, string Message, T Data) LoadJson(string fileName, string filePath) where T : new() { try { var result = LoadText(fileName, filePath); if (!result.OK) { return (false, result.Message, default(T)); } T data = JsonUtility.FromJson(result.Content); if (data == null) { return (false, "Ошибка десериализации JSON", default(T)); } return (true, $"JSON успешно загружен: {fileName}", data); } catch (Exception ex) { return (false, $"Ошибка загрузки JSON: {ex.Message}", default(T)); } } public static (bool OK, string Message, T Data) LoadJson(string fileName, AppDirectory directory) where T : new() => LoadJson(fileName, GetDirectoryName(directory)); public enum AppDirectory { Streaming, Persistent } }