Unity3D里简单的读取配置文件的工具类

using UnityEngine;

public class ConfigManager
{
    static Dictionary<string, string> config;

    static void loadSetting()
    {
        config = new Dictionary<string, string>();
        var path = Application.streamingAssetsPath;
        // 一个读取streamasset内文本文件的工具函数
        string str = StreamingAssetUtils.GetStreamingPathStr(Path.Combine(path, "setting.txt"));
        Debug.Log("read setting data complete! content=" + str);
        string[] lines = str.Split("\r\n");
        foreach(string line in lines)
        {
            string removesharp = "";
            int sharp = line.IndexOf('#');
            if (sharp >= 0)
                removesharp = line.Substring(0, sharp);
            else
                removesharp = line;

            string[] linesplit = removesharp.Split('=');
            if (linesplit.Length == 2)
            {
                if (config.ContainsKey(linesplit[0]))
                {
                    config[linesplit[0]] = linesplit[1];
                }
                else
                {
                    config.Add(linesplit[0], linesplit[1]); 
                }
            }
        }

        Debug.Log("config count = " + config.Count);
    }

    public static string getConfig(string key)
    {
        if (config == null)
            loadSetting();

        var count = config.Count;

        if (!config.ContainsKey(key))
        {
            Debug.LogError(key + "is not in setting");
            return "";
        }
        Debug.Log("config result = " + key + ":[" + config[key]+"]");
        return config[key].Trim();
    }

}

一个简单的读取配置文件的程序。建立一个setting.txt的文本文件放在StreamingAsset文件夹下。

内容格式为 key=value的形式

以#符号开头作为注释。

希望帮助到有需要的人。

补充:

关于读取streamingasset目录下文件的函数

    public static string GetStreamingPathStr(string path)
    {
        string fileStr = "";
        var uri = new System.Uri(path);
        var request = UnityWebRequest.Get(uri);

        var www = request.SendWebRequest();
        if (request.isNetworkError || request.isNetworkError)
        {
            Debug.Log(request.error);
        }
        else
        {
            while (true)
            {
                if (!request.isDone) continue;
                fileStr = request.downloadHandler.text;
                break;
            }
        }
        return fileStr;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值