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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM