unity | 添加和读取配置文件的可行方法

Statement:Windows下可用,其他OS平台未测试

首先我们需要Assets文件夹下添加所需的配置文件,这里以txt配置服务端IP和Port为例。

配置文件如下:

注意:

1. 在unity 编辑器里面运行,配置文件放在在Assets文件夹下,使用CurrentDirectory来获取Assets目录路径,进而获取配置文件

2. 将游戏打包成exe后,Application.dataPath指向exe同级目录,所以需要在exe同级目录再放一个配置文件供读写(Windows)

 在脚本中加入函数,用以访问配置文件(数据文件)

    public void GetIPAndPort()
    {
        // 使用dataPath得到游戏的“当前”路径
        // 1. 在unity 编辑器里面运行,配置文件放在在Assets文件夹下,使用CurrentDirectory来获取Assets目录路径,进而获取配置文件
        // 2. 将游戏打包成exe后,Application.dataPath指向exe同级目录,所以需要在exe同级目录再放一个配置文件供读写(Windows)
        string configFile = Application.dataPath + "/config.txt";
#if !UNITY_EDITOR
        configFile = System.Environment.CurrentDirectory + "/config.txt";
#endif
        if (File.Exists(configFile))
        {
            string[] strs = File.ReadAllLines(configFile);
            if (strs.Length < 2)
                return;
            for(int i=0; i<strs.Length; i++)
            {
                strs[i] = strs[i].Replace(" ", "");
            }
            try
            {
                host = strs[0].Replace("server=", "");
                port = int.Parse(strs[1].Replace("port=", ""));
            }
            catch (Exception)
            {
          //...异常逻辑
return; } } }

之后就可以调用函数访问到配置文件数据,进而使用数据了。

文章首发及更新于博客园 yocichen 

参考:

https://www.cnblogs.com/coolbear/p/9262101.html#4599255

https://blog.csdn.net/BillCYJ/article/details/99712313

https://blog.csdn.net/s15100007883/article/details/79134982

posted @ 2020-06-14 15:17  yocichen  阅读(1953)  评论(0编辑  收藏  举报