unity读取txt配置文件

本文介绍了一种使用Unity进行游戏开发时配置文件的解析方法,包括如何读取文本资产(TextAsset)并将其转换为可操作的数据结构。文章详细展示了如何通过自定义的配置文件读取器(FbConfigReader)来加载不同类型的配置数据,并提供了具体的实现类如ConfigBallParamTXT等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读配置文件,大同小异。1:看了宣雨松的博客开始是用sqlite,之后碰到一个移动盒子的问题,写入不到里面,就放弃了。

2:之后用了同事的ExcelTool,自动帮你读取excel文件,还能ab打包,但是之后遇到同事自己写的一个ab打包框架,又要改读取配置方式。

所以最终用读取txt文件。

a:还是用之前的excel文件,转换成txt文件。

b:总共三个类,一个解析类,一个读取类,一个是具体信息类去解析。具体代码提交看看!


using UnityEngine;
using System.Collections;

public interface IFbConfigReader
    {
        void LoadConfig(TextAsset txtAsset);

        int GetInt(string key);

        float GetFloat(string key);

        string GetString(string key);

        Hashtable GetHashtable(string key);

        Hashtable GetTable();

        bool pushTable(Hashtable t);

        void pop();
    }using System;
using UnityEngine;
using System.Collections;

public class FbConfigReader : IFbConfigReader
{
    private Hashtable _configTables;

    private Hashtable _stackTables;

    public FbConfigReader()
    {
        _configTables = new Hashtable();
    }

    public void LoadConfig(TextAsset txtAsset)
    {
        if(txtAsset==null)
        {
            Debug.Log("txtAsset is null!");
        }
       // TextAsset textAsset = Resources.Load(filePath, typeof(TextAsset)) as TextAsset;
        string[] lineArray = txtAsset.text.Split('\r');

        if (lineArray == null || lineArray.Length <= 1)
        {
            return;
        }

        string[] keys = lineArray[1].Split("\t"[0]);
        for (int i = 3; i < lineArray.Length; i++)
        {
            string[] arrays = lineArray[i].Split("\t"[0]);

            Hashtable tmpTable = new Hashtable();
            for (int j = 0; j < arrays.Length; j++)
            {
                string key = keys[j].Replace("\n", String.Empty);
                string value = arrays[j].Replace("\n", String.Empty);
                tmpTable.Add(key, value);
            }
            string key0 = keys[0].Replace("\n", String.Empty);
            if (!(tmpTable[key0] == null))
            {
                try
                {
                    int keyId = int.Parse(tmpTable[key0].ToString());
                    _configTables.Add("" + keyId, tmpTable);
                }
                catch (FormatException e)
                {

                }
            }
        }
        _stackTables = _configTables;
    }

    public new int GetInt(string key)
    {
        int val = 0;
        try
        {
            if (_stackTables[key] == null) return val;

            val = int.Parse(_stackTables[key].ToString());
        }
        catch (FormatException e)
        {

        }
        return val;
    }

    public new float GetFloat(string key)
    {
        float val = 0f;
        try
        {
            if (_stackTables[key] == null) return val;

            val = float.Parse(_stackTables[key].ToString());
        }
        catch (FormatException e)
        {

        }
        return val;
    }

    public new Hashtable GetTable()
    {
        return _configTables;
    }

    public new string GetString(string key)
    {
        return _stackTables[key].ToString();
    }

    public new Hashtable GetHashtable(string key)
    {
        return _stackTables[key] as Hashtable;
    }

    public new bool pushTable(Hashtable t)
    {
        _stackTables = t;

        return true;
    }

    public new void pop()
    {
        _stackTables = _configTables;
    }
}using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class FbConfigBallParamMgr :MonoBehaviour{

    private static FbConfigBallParamMgr mInstance;
    public static FbConfigBallParamMgr getInstance()
    {
        if(mInstance==null)
        {
            GameObject gb = new GameObject("FbConfigBallParamMgr");
            mInstance = gb.AddComponent();
            DontDestroyOnLoad(gb);
        }
        return mInstance;
    }

    private IFbConfigReader _ballParamsReader;
    private IFbConfigReader _shootAreaReader;
    private IFbConfigReader _shootBulletBallReader;
    public List listData = new List();

    private bool _bReadConfig = false;
    public bool bReadConfig
    {
        get { return _bReadConfig; }
    }
    public void LoadConfig(string path, Action fnFinish)
    {
        IxLoader.ON_LOAD_FINISH fnLoadFinish = delegate (string strURL2, WWW kW, object kArg)
        {
            if (!string.IsNullOrEmpty(kW.error))
            {
                Logger.LogError("Load game config failed: " + kW.error);
                kW.Dispose();

                if (fnFinish != null)
                {
                    fnFinish(false);
                }
                return;
            }

            Logger.Log("Load game config done.");

            if (kW.assetBundle == null)
            {
                Logger.LogError("Game config asset bundle is null.");
                kW.Dispose();

                if (fnFinish != null)
                {
                    fnFinish(false);
                }
                return;
            }
            TextAsset kTA = kW.assetBundle.LoadAsset("BallParam");
            if (kTA == null)
            {
                Logger.LogError("Load game config TextAsset failed.");
                kW.assetBundle.Unload(true);
                kW.Dispose();

                if (fnFinish != null)
                {
                    fnFinish(false);
                }
                return;
            }
            //
            _ballParamsReader = ReadData(kTA);

            //射球区域解析
            kTA = kW.assetBundle.LoadAsset("shootArea");
            if (kTA == null)
            {
                Logger.LogError("Load game config TextAsset failed.");
                kW.assetBundle.Unload(true);
                kW.Dispose();

                if (fnFinish != null)
                {
                    fnFinish(false);
                }
                return;
            }
            _shootAreaReader = ReadData(kTA);

            //
            //子弹模式解析
            kTA = kW.assetBundle.LoadAsset("ShootBulletBall");
            if (kTA == null)
            {
                Logger.LogError("Load game config TextAsset failed.");
                kW.assetBundle.Unload(true);
                kW.Dispose();

                if (fnFinish != null)
                {
                    fnFinish(false);
                }
                return;
            }
            _shootBulletBallReader = ReadData(kTA);
            //
            _bReadConfig = true;

            kW.assetBundle.Unload(true);
            kW.Dispose();

            if (fnFinish != null)
            {
                fnFinish(true);
            }
        };


        string strURL = IxURL.ConvertToLoadURL(path);
        IxLoader.ms_kSig.Load(strURL, null, fnLoadFinish);
    }

    public ConfigBallParamTXT GetBallParamInfoData(string id)
    {
        Hashtable t = _ballParamsReader.GetHashtable(id);
        if (t != null)
        {
            _ballParamsReader.pushTable(t);
            ConfigBallParamTXT productInfoData = new ConfigBallParamTXT();
            productInfoData.Read(_ballParamsReader);
            _ballParamsReader.pop();
            return productInfoData;
        }
        return null;
    }

    public ConfigShootAreaTXT GetShootAreaInfoData(string id)
    {
        Hashtable t = _shootAreaReader.GetHashtable(id);
        if (t != null)
        {
            _shootAreaReader.pushTable(t);
            ConfigShootAreaTXT productInfoData = new ConfigShootAreaTXT();
            productInfoData.Read(_shootAreaReader);
            _shootAreaReader.pop();
            return productInfoData;
        }
        return null;
    }

    public ConfigShootBulletBallTXT  GetShootBulletInfoData(string id)
    {
        Hashtable t = _shootBulletBallReader.GetHashtable(id);
        if (t != null)
        {
            _shootBulletBallReader.pushTable(t);
            ConfigShootBulletBallTXT productInfoData = new ConfigShootBulletBallTXT();
            productInfoData.Read(_shootBulletBallReader);
            _shootBulletBallReader.pop();
            return productInfoData;
        }
        return null;
    }

    private IFbConfigReader ReadData(TextAsset assets)
    {
        IFbConfigReader reader = new FbConfigReader();
        reader.LoadConfig(assets);
        //Hashtable fbTable = reader.GetTable();
        //if(fbTable ==null)
        //{
        //    Debug.Log("fbtable  ball==null!");
        //}

        //foreach (Hashtable item in fbTable.Values)
        //{
        //   if(item!=null)
        //    {
        //        ConfigBallParamTXT  info = new ConfigBallParamTXT ();
        //        info.Read(item);
        //        listData.Add(info);
        //    }
        //}
        return reader;
    }
}using UnityEngine;
using System.Collections;

public class ConfigBallParamTXT  {

    public int id;
    public float velocity;
    public float timeGap;
    public string areaIndex;
    public string shootCurve;
    public float polePosZ;
    public string ballColor;

    public void Read(Hashtable t)
    {
        if (t == null) return;

        id = int.Parse(t["id"].ToString());
        velocity = float.Parse(t["velocity"].ToString());
        timeGap = float.Parse(t["timeGap"].ToString());
        polePosZ = float.Parse(t["polePosZ"].ToString());

        areaIndex = t["areaIndex"].ToString();
        shootCurve = t["shootCurve"].ToString();
        ballColor = t["ballColor"].ToString();
    }

    public  void Read(IFbConfigReader reader)
    {
        if (reader == null) return;

        id = reader.GetInt("id");
        velocity = reader.GetFloat("velocity");
        timeGap = reader.GetFloat("timeGap");
        polePosZ = reader.GetFloat("polePosZ");

        areaIndex =reader.GetString("areaIndex");// t["areaIndex"].ToString();
        shootCurve = reader.GetString("shootCurve");
        ballColor = reader.GetString("ballColor");
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值