*切换到串行化。
摘要:我已将所有变量预定义为 null / 0。我想使用来自 XML 文档的数据来设置它们。该文档包含与变量完全相同的名称。我不想使用一堆 else if,所以我试图根据我从 XML 文档中提取的名称来做。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
using System.IO;
public class ShipAttributes
{
// Model Information
string name;
string modelName;
string firingPosition;
string cameraPosition;
string cargoPosition;
Vector3 cameraDistance;
// Rotation
float yawSpeed;
float pitchSpeed;
float rollSpeed;
// Speed
float maxSpeed;
float cruiseSpeed;
float drag;
float maxAcceleration;
float maxDeceleration;
// Physics Properties
float mass;
// Collection Capacity
float cargoSpace;
// Combat [Defense]
float structureHealth;
float armorHealth;
float shieldHealth;
float shieldRadius;
// Combat [Assault]
float missileRechargeTime;
float fireRate;
// Currency Related
float cost;
float repairMultiplier;
void PopulateShipList()
{
if (shipList != null)
return;
string filepath = Application.dataPath + "/Resources/shipsdata.xml";
XmlRootAttribute xml_Root = new XmlRootAttribute();
xml_Root.ElementName = "SHIPS";
xml_Root.IsNullable = true;
//using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
//{
StringReader stringReader = new StringReader(filepath);
stringReader.Read();
XmlReader xRdr = XmlReader.Create(stringReader);
XmlSerializer xml_s = new XmlSerializer(typeof(List<ShipAttributes>), xml_Root);
shipList= (List<ShipAttributes>)xml_s.Deserialize(xRdr);
//}
}
public ShipAttributes LoadShip(string inName)
{
PopulateShipList();
foreach (ShipAttributes att in shipList)
{
if (att.name == inName)
{
att.shipList = shipList;
return att;
}
}
return null;
}
*注意 XML 文件中的变量与类中的变量具有完全相同的格式和名称。类中的 maxSpeed 是 XML 文件中的 maxSpeed。
我的 XML 看起来像这样——
<?xml version="1.0" encoding="UTF-8 without BOM" ?>
<SHIPS>
<SHIP>
<name>Default</name>
<id>0</id>
<modelName>Feisar_Ship</modelName>
<firingPosition>null</firingPosition>
<cameraPosition>null</cameraPosition>
<cargoPosition>null</cargoPosition>
<cameraDistance>null</cameraDistance>
<yawSpeed>2000.0</yawSpeed>
<pitchSpeed>3000.0</pitchSpeed>
<rollSpeed>10000.15</rollSpeed>
<maxSpeed>200000.0</maxSpeed>
<cruiseSpeed>100000.0</cruiseSpeed>
<drag>0.0</drag>
<maxAcceleration>null</maxAcceleration>
<maxDeceleration>null</maxDeceleration>
<mass>5000.0</mass>
<cargoSpace>150.0</cargoSpace>
<structureHealth>100.0</structureHealth>
<armorHealth>25.0</armorHealth>
<shieldHealth>25.0</shieldHealth>
<shieldRadius>30.0</shieldRadius>
<missileRechargeTime>2.0</missileRechargeTime>
<fireRate>0.5f</fireRate>
<cost>0</cost>
<repairMultiplier>1.0</repairMultiplier>
</SHIP>
</SHIPS
>
是的,是的,我知道……费萨尔!现在只是来自turbosquid的占位符。