using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
public class INIReader : MonoBehaviour
{
// INI文件路径
public string filePath = "config.ini";
// INI文件中的键值对
private Dictionary<string, Dictionary<string, string>> keyValuePairs = new Dictionary<string, Dictionary<string, string>>();
void Start()
{
ReadINIFile();
}
// 读取INI文件
private void ReadINIFile()
{
if (!File.Exists(filePath))
{
Debug.LogError("File does not exist: " + filePath);
return;
}
// 读取文件内容
string[] lines = File.ReadAllLines(filePath);
string section = "";
foreach (string line in lines)
{
// 去除注释
string content = line.Trim();
int index = content.IndexOf(";");
if (index >= 0)
{
content = content.Substring(0, index);
}
// 处理节名
if (content.StartsWith("[") && content.EndsWith("]"))
{
section = content.Substring(1, content.Length - 2);
if (!keyValuePairs.ContainsKey(section))
{
keyValuePairs.Add(section, new Dictionary<string, string>());
}
}
// 处理键值对
else if (section.Length > 0)
{
index = content.IndexOf("=");
if (index >= 0)
{
string key = content.Substring(0, index).Trim();
string value = content.Substring(index + 1).Trim();
if (!keyValuePairs[section].ContainsKey(key))
{
keyValuePairs[section].Add(key, value);
}
}
}
}
}
// 获取指定节和键的值
public string GetStringValue(string section, string key, string defaultValue = "")
{
if (keyValuePairs.ContainsKey(section) && keyValuePairs[section].ContainsKey(key))
{
return keyValuePairs[section][key];
}
return defaultValue;
}
public int GetIntValue(string section, string key, int defaultValue = 0)
{
string value = GetStringValue(section, key);
int result;
if (int.TryParse(value, out result))
{
return result;
}
return defaultValue;
}
public float GetFloatValue(string section, string key, float defaultValue = 0.0f)
{
string value = GetStringValue(section, key);
float result;
if (float.TryParse(value, out result))
{
return result;
}
return defaultValue;
}
}
INIReader reader = GetComponent<INIReader>();
string name = reader.GetStringValue("Person", "Name");
int age = reader.GetIntValue("Person", "Age");
float height = reader.GetFloatValue("Person", "Height");
以下是一个示例的INI文件:
[Person]
Name=John
Age=30
Height=1.75