文章17
标签2
分类9

Unity调用File Explorer读取文件地址

读取文件地址

string image_path = EditorUtility.OpenFilePanel("Overwrite with png", "", "png");

path就是读取的地址,可用于文件读取操作。

读取图片

public Sprite load_sprite(string path)
    {
        if (string.IsNullOrEmpty(path)) return null;
        if (System.IO.File.Exists(path))
        {
            byte[] bytes = System.IO.File.ReadAllBytes(path);
            Texture2D texture = new Texture2D(1, 1);
            texture.LoadImage(bytes);
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            return sprite;
        }
        return null;
    }

读取CSV

Dictionary<int, Data.Dialogue> csv_list = new Dictionary<int, Data.Dialogue>();    

public void read_csv(string filePath)
    {
        /* 把CSV文件按行存放,每一行的ID作为key值,内容作为value值 */
        /* 从CSV文件读取数据 */
        Dictionary<int, Dictionary<string, string>> datasDic = LoadCsvFile(filePath);
        /* 遍历每一行数据 */
        foreach (int ID in datasDic.Keys)
        {
            /* CSV的一行数据 */
            Dictionary<string, string> datas = datasDic[ID];
            /* 读取Csv数据对象的属性 */

            Data.Dialogue obj = new Data.Dialogue();

            obj.id = Convert.ToInt32(datas["int_id"]);
            obj.act_number = Convert.ToInt32(datas["int_act_number"]);
            obj.character_1_name = datas["string_character_1_name"];
            obj.character_2_name = datas["string_character_2_name"];
            obj.dialogue_text = datas["string_dialogue_text"];
            obj.background_name = datas["string_background_name"];

            /* 按ID-数据的形式存储 */
            csv_list[obj.id] = obj;
        }
    }

   static Dictionary<int, Dictionary<string, string>> LoadCsvFile(string filePath)
    {
        Dictionary<int, Dictionary<string, string>> result = new Dictionary<int, Dictionary<string, string>>();
        string[] fileData = File.ReadAllLines(filePath);
        /* CSV文件的第一行为Key字段,第二行开始是数据。第一个字段一定是ID。 */
        string[] keys = fileData[0].Split(',');
        for (int i = 1; i < fileData.Length; i++)
        {
            string[] line = fileData[i].Split(',');
            /* 以ID为key值,创建一个新的集合,用于保存当前行的数据 */
            result[i] = new Dictionary<string, string>();
            for (int j = 0; j < line.Length; j++)
            {
                /* 每一行的数据存储规则:Key字段-Value值 */
                result[i][keys[j]] = line[j];
            }
        }

        return result;
    }

其中保存的Dialogue变量如下

public class Dialogue
    {
        public int id;
        public int act_number;
        public string background_name;
        public string character_1_name;
        public string character_2_name;
        public string dialogue_text;
    }
本文作者:admin
本文链接:https://banned.top/archives/19/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可

0 评论

'