Unity学习笔记:读取配置文件
程序员文章站
2022-07-12 13:03:32
...
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
/// <summary>
///
/// </summary>
public class ConfigTest : MonoBehaviour
{
private Dictionary<string, Dictionary<string, string>> dic
= new Dictionary<string, Dictionary<string, string>>();
private string path;
private void Start()
{
//读取StreamingAssets文件下的文件路径
path = Path.Combine(Application.streamingAssetsPath,
"Config.txt");
LoadConfig();
}
//读取所有数据
private void LoadConfig()
{
string[] lines = null;
if (File.Exists(path))
{
lines = File.ReadAllLines(path);
BuildDic(lines);
}
}
//处理所有数据
private void BuildDic(string[] lines)
{
//主键
string mainKey = null;
//子键
string subKey = null;
//值
string subValue = null;
foreach (var item in lines)
{
string line = null;
line = item.Trim();//去除空行
if (!string.IsNullOrEmpty(line))
{
//取主键
if (line.StartsWith("["))
{
mainKey = line.Substring(1, line.IndexOf("]") - 1);
dic.Add(mainKey, new Dictionary<string, string>());
}
//取子键以及值
else
{
var configValue = line.Split('=');
subKey = configValue[0].Trim();
subValue = configValue[1].Trim();
subValue = subValue.StartsWith("\"") ? subValue.Substring(1) : subValue;
dic[mainKey].Add(subKey, subValue);
}
}
}
}
private void OnGUI()
{
GUILayout.Label(dic["Login"]["Password"]);
}
}
文件txt
下一篇: Unity 读取配置文件