Unity 中System.Runtime.InteropServices读取配置文件

首先得创建一个读取ini配置文件的基类,创建好一个后,后面项目需要都可以直接拿来用了
创建基类得引用命名空间 System.Runtime.InteropServices
下面为基类代码:

public class MyIni
{
  public string path;//ini文件的路径
  public MyIni(string path)
  {
    this.path=path;
  }
  [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);

//写入ini文件
public void WriteIniContent(string section,string key,string value)
{
WritePrivateProfileString(section,key,value,this.path);
}

//读取Ini文件
public string ReadIniContent(string section,string key)
{
   StringBuilder temp=new StringBuilder(255);
   int i=GetPrivateProfileString(section,key,"",temp,255,this.path);
   return temp.ToString();
}

//判断路径是否正确
public bool IsIniPath()
{
   return File.Exists(this.path);
}
}

函数的使用,得先创建一个txt文本文件然后写入内容
内容格式为大标题“[]”,对应大标题下的内容 “名字(相当于key值)=value(使用中文的话可能会有问题,需要转码,中文的话一般使用xml文档)”

[Time] 
time=10 
[Speed] 
speed=5 

类似这样的写法,然后保存为ini文件,拖拽到项目中StreamingAssets位置,一般都是放在这个路径
下面是函数的调用:

public class IniDemo
{
    MyIni ini;

    private int  time=0;
    private float speed=0;
    void Start()
    {
      //获取ini文件
      ini=new MyIni(Application.StreamingAssets+"/Setting.ini");
      //获取Ini文件Time类型下的time对应的数值
      time=ini.ReadIniContent("Time","time");
      speed=ini.ReadIniContent("Speed","speed");
      //写入Count类型count值对应的数值(如果存在了相同的key会覆盖原来key的内容)
      ini.WritePrivateProfileString("Count","count","5");
    }
}

基本上一个简单的ini配置文件的使用就OK了,当然你喜欢的话还可以对基类就行添加函数,添加对一整个大类型直接读取,这都是可以的,不过基本上也够用了。

posted @ 2022-06-16 15:35  嘿,阿然  阅读(336)  评论(0编辑  收藏  举报