using System;
using System.Xml.Linq;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
public static class ReadXML<T> where T : class
{
private static string path;
private static T target;
static ReadXML()
{
}
private static void SetXmlPath(string p)
{
path = p;
}
private static XElement LoadXML()
{
if (path == null)
return null;
TextAsset textAsset = (TextAsset)Resources.Load(path);
XElement xml = XElement.Parse(textAsset.text);
return xml;
}
private static void CreateInitiate()
{
Type t = typeof(T);
ConstructorInfo ct = t.GetConstructor(System.Type.EmptyTypes);
target = (T)ct.Invoke(null);
}
public static List<T> ReadElements(string path)
{
SetXmlPath(path);
List<T> ts = new List<T>();
XElement xml = LoadXML();
foreach (XElement xe in xml.Elements())
{
ts.Add(ReadElement(xe));
}
return ts;
}
private static T ReadElement(XElement xml)
{
if (target != null)
{
target = null;
}
CreateInitiate();
Type t = target.GetType();
FieldInfo[] fields = t.GetFields();
string fieldName = string.Empty;
foreach (FieldInfo f in fields)
{
fieldName = f.Name;
if (xml.Attribute(fieldName) != null)
{
f.SetValue(target, Convert.ChangeType(xml.Attribute(fieldName).Value, f.FieldType));
}
}
return target;
}
}
public Dictionary<int, PassCheck_Reward> GetPassCheckRewardDicConfig(List<PassCheck_Reward> list)
{
Dictionary<int, PassCheck_Reward> dic = new Dictionary<int, PassCheck_Reward>();
int count = list.Count;
for (int i = 0; i < count; i++)
{
if (!dic.ContainsKey(list[i].level))
{
dic.Add(list[i].level, list[i]);
}
}
return dic;
}
public Dictionary<int, PassCheck_Reward> passCheckRewardDic = new Dictionary<int, PassCheck_Reward>();
passCheckRewardDic = GetPassCheckRewardDicConfig(ReadXML<PassCheck_Reward>.ReadElements(ConstData.PassCheckDataPath));