Unity读取.ini配置文件
写一下方法
``` using UnityEngine; using System.Runtime.InteropServices; using System.Text; using System.IO;
public class myAppConfig {
[DllImport("kernel32")]
public static extern long WritePrivateProfileString(string section, string key, string value, string path);
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string section, string key, string deval, StringBuilder stringBuilder, int size, string path);
public string path;//ini文件的路径
public myAppConfig(string path)
{
if (IsIniPathExists(Path.Combine(Application.streamingAssetsPath, path)) == true)
{
this.path = Path.Combine(Application.streamingAssetsPath, path);
}
else
{
Debug.LogError("配置文件路径错误");
}
}
/// <summary>
/// 写入ini文件
/// </summary>
/// <param name="section">参数段名称</param>
/// <param name="key">参数key</param>
/// <param name="value">参数value</param>
public void WriteIniContent(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, this.path);
}
/// <summary>
/// 读取Ini文件
/// </summary>
/// <param name="section">参数段名称</param>
/// <param name="key">参数的key</param>
/// <returns></returns>
public string ReadIniContent(string section, string key)
{
StringBuilder temp = new StringBuilder(255);
GetPrivateProfileString(section, key, "", temp, 255, this.path);
return temp.ToString();
}
/// <summary>
/// 删除文件,整个section
/// </summary>
/// <param name="section">参数段名称</param>
/// <returns></returns>
public void DeleteIniContentAll(string section)
{
WritePrivateProfileString(section, null, null, this.path);
}
/// <summary>
/// 删除文件,单独某个参数
/// </summary>
/// <param name="section">参数段名称</param>
/// <param name="key">参数的key</param>
/// <returns></returns>
public void DeleteIniContentOne(string section, string key)
{
WritePrivateProfileString(section, key, null, this.path);
}
/// <summary>
/// 判断路径是否存在
/// </summary>
/// <param name="paht">路径</param>
/// <returns></returns>
public bool IsIniPathExists(string paht)
{
return File.Exists(paht);
}
}
```
使用
在创建一个物体然后在物体上挂在这个脚本就行啦
``` using UnityEngine;
public class myIni : MonoBehaviour { myAppConfig ini;
void Start()
{
//获取ini文件
ini = new myAppConfig(Application.streamingAssetsPath + @"/AppConfig/SysConfig.ini");
string speed = ini.ReadIniContent("Speed", "runSpeed");
string nameStr = ini.ReadIniContent("Name", "enemyName");
string nameInt = ini.ReadIniContent("Name", "myName");
Debug.Log(speed);
Debug.Log(nameStr);
Debug.Log(nameInt);
ini.WriteIniContent("Count", "count", "1");//写入
ini.WriteIniContent("Count", "count", "1");//写入
ini.DeleteIniContentAll("Time");//删除一组
ini.DeleteIniContentOne("Speed", "speed");//删除一行
}
}
测试的ini文件,文件名称为:SysConfig,文件夹名称为:AppConfig
[Speed] speed=123 runSpeed=1 sleepSpeed=2 [Time] runTime=1 [Name] enemyName=menemyName123 myName="myName123" CubeName="cubeName123" [Count] hunManCount=3 weaponCount=10 ```
运行效果
。