Unity中加載文本

關鍵代碼

// 加載本地文本 注意"/"
string path1 = Application.dataPath + "/Test.txt";
string text1 = System.IO.File.ReadAllText(path1);

// 加載Resources下的文本 注意不寫後綴
string path2 = "Test";
TextAsset textAsset = Resources.Load<TextAsset>(path2);
string text2 = textAsset.text;

Unity TextAsset支持的後綴格式:html

  • .txt
  • .xml
  • .json
  • .bytes
  • .csv
  • .fnt
  • .htm
  • .html
  • .yaml

封裝

TextLoader.csjson

using System.IO;
using UnityEngine;

/// <summary>
/// 文本加載器
/// <para>ZhangYu 2017-12-24</para>
/// </summary>
public static class TextLoader {

    // 加載本地文本
    public static string localLoad(string path){
        if (!File.Exists(path)) return null;
        return File.ReadAllText(path);
    }

    // 加載Resources下的文本
    public static string resourcesLoad(string path) {
        TextAsset textAsset = Resources.Load<TextAsset>(path);
        if (textAsset == null) return null;
        return textAsset.text;
    }

    // 保存本地文本
    public static void localSave(string path, string text){
        if (!File.Exists(path)) {
            FileStream stream = File.Create(path);
            stream.Close();
            stream.Dispose();
        }
        File.WriteAllText(path, text);
    }
}

注意事項:

文本放在Resources下時,要注意後綴是不是Unity支持的格式。
加載時不須要填寫後綴名稱,相同路徑下的不一樣類型文件不要重名,不然加載時可能會選錯文件。
Unit支持的格式能夠預覽
圖片描述spa

相關文章
相關標籤/搜索