On the previous implementation of the engine, all the game configuration was hardcoded into the game
. With the Unity port I want to make most of the game parameters configurable from external files, so I started to implement this.At long term this is a quite a good decission. Another person can adjust all parameters without any recompiling.
As a first attempt, I wanted to make all the weapons of the game configurable from an XML file.
This is my sample XML. Here, I define two weapons, with several fields including weapon damage and firing speed.
<?xml version="1.0"?>
<Weaponry>
<Weapon>
<weaponName>weapon1</weaponName>
<damage>1</damage>
<chargingSec>1</chargingSec>
<firingSec>1</firingSec>
<coolDownSec>1</coolDownSec>
<damageWidth>1</damageWidth>
<damageHeight>1</damageHeight>
<chaineable>true</chaineable>
</Weapon>
<Weapon>
<weaponName>weapon2</weaponName>
<damage>1</damage>
<chargingSec>1</chargingSec>
<firingSec>1</firingSec>
<coolDownSec>1</coolDownSec>
<damageWidth>1</damageWidth>
<damageHeight>1</damageHeight>
<chaineable>true</chaineable>
</Weapon>
</Weaponry>
Inside my code, I created the 'weapon' and 'weaponry' objectss:
[DataContract(Name = "Weapon", Namespace = "")]
public class Weapon
{
[DataMember] private Boolean chaineable;
[DataMember] private float chargingSec;
[DataMember] private float coolDownSec;
[DataMember] private int damage;
[DataMember] private float damageHeight;
[DataMember] private float damageWidth;
[DataMember] private float firingSec;
[DataMember] private String weaponName;
...
[KnownType(typeof (Weapon))]
[CollectionDataContract(Name = "Weaponry", ItemName = "Weapon", Namespace = "")]
public class Weaponry : List<Weapon>
{
}
Finally, to read the XML file and access to any weapon from its name, I created this static method:
public class WeaponryDataBase
{
private static Weaponry weaponry;
public static Weapon getWeapon(String name)
{
if (weaponry == null)
initialize();
foreach (Weapon weapon in weaponry)
{
if (weapon.WeaponName.Equals(name)) return weapon;
}
throw new Exception("Weapon " + name + " not found");
}
private static void initialize()
{
string fileName = Path.Combine(Path.GetDirectoryName(Application.dataPath), "Weaponry.xml");
var dcs = new DataContractSerializer(typeof (Weaponry));
var fs = new FileStream(fileName, FileMode.Open);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
weaponry = (Weaponry) dcs.ReadObject(reader);
reader.Close();
fs.Close();
}
}
The method initializes the weaponry database, this means that it reads the file and parse it to a list of 'weapon' objects.
This is great!
now I will be able to change any weapon parameters just by touching the config file. At the end this has been easier to make than I though.