ConfigHelper.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using LitJson;
  2. using System.IO;
  3. using UnityEngine;
  4. namespace WS
  5. {
  6. ///<summary>加载配置文件</summary>
  7. public static class ConfigHelper
  8. {
  9. ///<summary>加载配置文件</summary>
  10. public static T LoadConfig<T>(string path)
  11. {
  12. TextAsset asset = Resources.Load<TextAsset>(path);
  13. T t = JsonMapper.ToObject<T>(asset.text);
  14. return t;
  15. }
  16. ///<summary>全路径加载</summary>
  17. public static T FileLoadConfig<T>(string path) where T : new()
  18. {
  19. using (StreamReader sr = new StreamReader(path))
  20. {
  21. T config = JsonMapper.ToObject<T>(sr.ReadToEnd());
  22. if (config == null)
  23. {
  24. config = new T();
  25. }
  26. return config;
  27. }
  28. }
  29. /// <summary>保存Config</summary>
  30. public static void SaveConfig(object config, string path)
  31. {
  32. using (FileStream fileStream = new FileStream(path, FileMode.Create))
  33. {
  34. byte[] bytes = JsonMapper.ToJson(config).ToByteArray();
  35. fileStream.Write(bytes, 0, bytes.Length);
  36. }
  37. }
  38. /// <summary>文件是否存在 不存在则创建</summary>
  39. public static bool ConfigExists(string path)
  40. {
  41. if (File.Exists(path))
  42. {
  43. return true;
  44. }
  45. FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
  46. fs.Close();
  47. return true;
  48. }
  49. }
  50. }