Recently I had very sad post, about certain things in my project not working too well. Today I found and implemented solution to that issues.
As I said before, I was thinking about holding default need values in XML file. That’s exactly what I did. There is an XML file with defaults in project, so you can check it out (and set your own values if you like).
Few words about the implementation. It is not rocket science, but some of you might find it interesting.
So that’s how XML looks like:
<?xml version="1.0" encoding="UTF-8"?> <needs> <need> <need_type>Food</need_type> <value>50</value> </need> <need> <need_type>Water</need_type> <value>50</value> </need> </needs>
I think it speaks for itself. It basically holds list of objects, where each one of them has need_type and value property. Before I’ve made parsing code I needed a data structure.I used Xml2CSharp.com, these are classes generated from it (after some changes in datatypes):
[XmlRoot(ElementName = "need")] public class Need { [XmlElement(ElementName = "need_type")] public NeedType NeedType { get; set; } [XmlElement(ElementName = "value")] public double Value { get; set; } } [XmlRoot(ElementName = "needs")] public class Needs { [XmlElement(ElementName = "need")] public List<Need> Need { get; set; } }
I could propably do it myself, but saddly I am lazy person. Anyway, this solution works just fine, so it stays that way for now.
And finally – InitializeNeeds method
public static void InitializeNeeds(PillAi pillAI) { var path = "Assets\\Resources\\Needs.xml"; var reader = new XmlTextReader(path); var serializer = new XmlSerializer(typeof(Needs)); var defaults = (Needs)serializer.Deserialize(reader); foreach (var need in defaults.Need) { pillAI.Pill.Needs[need.NeedType] = need.Value; } }
This solution still needs some work, but it does what it should. Default need values are no longer hardcoded.
But still, it is far from the solution I imagined. Yes, you can edit the XML but only before you build the game. After that, all asset files are packed into*.asset files. I want them to be accesible in builded version, so that is unacceptable. In the next post I will find the way of doing that.
But for now – happy saturday! It’s the best day of the week, IMO 🙂
PS: I’ve updated „About me” page and it is in english now.