通过读取txt文件,避免直接在程序内进行更改数值,可以直接在txt更改游戏数据。这次写的框架是简单版,只能读不能存,大家可以继续扩充
用的是上次fsm框架的场景
首先把读取文件的代码封装一下---------------之后还会用到(Audio,sql…)代码并不是很难,我就不过多解释了
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class ReadIConfig
{
//不继承mono的单例
//读取其他文件之后还会用到,所以写成单例方便调用
static ReadIConfig instance;
public static ReadIConfig Instance
{
get
{
if (instance == null)
{
instance = new ReadIConfig();
}
return instance;
}
}
//用以dic把数据给存起来
public Dictionary<string,string > GetKeyValue(string fileName)
{
Dictionary<string, string> allData = new Dictionary<string, string>();
string path = Application.streamingAssetsPath + string.Format("/{0}", fileName);
//读取文件
StreamReader tmpReader = new StreamReader(path);
//解析有多少个Key Value 有多少行
string line = tmpReader.ReadLine();
int tmpCount = int.Parse(line);
for (int i = 0; i < tmpCount; i++)
{
line = tmpReader.ReadLine();
string[] lines = line.Split('|');
allData.Add(lines[0], lines[1]);
}
tmpReader.Close();
return allData;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingleData
{
public string Data;
public SingleData(string Data)
{
this.Data = Data;
}
}
public class TXTdata
{
Dictionary<string, string> data;
SingleData[] allData;
public TXTdata()
{
ChuShiHua();
}
public void ChuShiHua()
{
//这里可以把文件名字再提出来,继续封装一层
data = ReadIConfig.Instance.GetKeyValue("Monster.txt");
allData = new SingleData[data.Count];
}
public string GetDataName(string key)
{
return data[key];
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Readtxt : MonoBehaviour
{
public static Readtxt Instance;
private void Awake()
{
Instance = this;
txt = new TXTdata();
}
TXTdata txt;
public float LoadData(string key)
{
string dataName = txt.GetDataName(key);
if (!string.IsNullOrEmpty(dataName))
return float.Parse(dataName);
else
return 0;
}
}
用法:
public class StoneM
{
public float bloodCount;
public float attackPower;
public float skillOne;
public StoneM()
{
bloodCount = Data.Instance.LoadData("StoneBloodCount");
attackPower = Data.Instance.LoadData("StoneAttackPower");
skillOne = Data.Instance.LoadData("StoneSkillOne");
//Debug.Log("StoneBloodCount====" + bloodCount);
}
}