Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by HydroxTV · Apr 10, 2016 at 09:38 AM · xmlxmlserializer

RTS Import XML

Hello guys, I am quite new to Unity and Coding, and I have been googling for over 8hours to find a proper tutorial so i can learn how to do it myself. Unfortunately all tutorials are REALLY old and dont seem to work anymore.

What I try to achieve is having a XML file where I store data like this:

 <building>
 <id>0</id>
 <name>House1</name>
 <gold>100</gold>
 <wood>200</wood>
 </building>


Then Ingame I would like to have an Image when I hover them it shows the required Materials(in this case 100gold and 200wood) an if I do have the materials I can click it and place it.

The Issue I have is that I dont know how to get these Informations from XML over to Unity. Ive looked up XML-Serialization. Is this still the way? And If so...HOW do I achieve that? I would really appreciate your help and hints. Because I am going crazy ^^

It would be enough just to get the variable of the id over to unity as an example,I would do the rest on my own as I want to learn and not take premade code and have no clue what it is doing :)

Thanks in advance!

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image HydroxTV · Apr 10, 2016 at 10:01 PM 0
Share

"Infor$$anonymous$$g"

@ArkaneX as stated in http://answers.unity3d.com/questions/651714/learning-how-to-deserialize-xml-file.html#comment-1168699

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by ArkaneX · Apr 11, 2016 at 08:34 PM

I assume you know how to load/save xml, and that your main issue is to transform the xml string to/from actual object. I will provide sample with Id property only, as you requested :)

But before I start - in case of xml serialization, it's no difference if you do it in Unity or in any other C# application - all work exactly the same way. At least I haven't encountered any differences yet...

First thing, is to create a class with properties that map on elements in your xml file. In case of your building, the simplest class would be:

 public class building
 {
     public int id { get; set; }
 }

Sometimes it is necessary to decorate class and its properties with attributes, that inform serializer how to perform serialization and deserialization. For example, when I write C# classes, I always follow standard naming rules, so class name and property names always start with capital letter, so the class becomes:

 public class Building
 {
     public int Id { get; set; }
 }

Serializing an instance of this class, would produce xml like:

 <Building>
   <Id>1</Id>
 </Building>

because serializer doesn't know you want the xml attributes to be all lowercase. To fix this, you need attributes:

 [XmlRoot("building")]
 public class Building
 {
     [XmlElement("id")]
     public int Id { get; set; }
 }

If you want to use slightly more complicated xml, and serialize list of buildings, then you need two classes:

 [XmlRoot("buildings")]
 public class BuildingsCollection
 {
     [XmlElement("building")]
     public List<Building> Buildings { get; set; }
 }
 
 public class Building
 {
     [XmlElement("id")]
     public int Id { get; set; }
 }

Please note, that when you serialize BuildingsCollection class, you no longer need XmlRoot attribute on Building class - attribute on BuildingCollection.Buildings property handles this case. If, however, you sometimes want to serialize BuildingsCollection, and sometimes Building, then you should add that attribute back.

Don't forget about required namespaces: System.Collections.Generic, and for attributes: System.Xml.Serialization.

If you need to create more complex classes, you need to read a bit more about serialization. You can try some online tools as well, e.g. this xml to C# classes converter

After you created the class/classes, the only thing left is to actually serialize/deserialize. You can use simple helper:

 using System.IO;
 using System.Text;
 using System.Xml.Serialization;

 public class SerializationHelper
 {
     public static string Serialize<T>(T data)
     {
         var sb = new StringBuilder();
         var serializer = new XmlSerializer(typeof(T));
         using (var writer = new StringWriter(sb))
         {
             serializer.Serialize(writer, data);
         }
         return sb.ToString();
     }
 
     public static T Deserialize<T>(string xml)
     {
         var serializer = new XmlSerializer(typeof(T));
         using (var reader = new StringReader(xml))
         {
             return (T)serializer.Deserialize(reader);
         }
     }
 }

and then call it like:

 var xml = SerializationHelper.Serialize(new Building { Id = 1 });
 var buildingCollection = SerializationHelper.Deserialize<BuildingsCollection>(@"
 <buildings>
     <building>
         <id>10</id>
     </building>
     <building>
         <id>20</id>
     </building>
 </buildings>");

When you serialize the data, resulting xml will contain some additional data - xml declaration at the beginning, and attributes in the root element. That's perfectly ok.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image HydroxTV · Apr 18, 2016 at 12:55 PM 0
Share

That answer was amazing :) So detailed ... I am baffled how detailed it is. Now I do understand the serialization/deserialization process way more :)

Actually I figured out what my problem with http://wiki.unity3d.com/index.php?title=Saving_and_Loading_Data:_XmlSerializer was. I never used the execution line in like Start() or Update(). Cause I am VERY new to this. Now after 1.5 Weeks and about 12hours/day I made quite some progress.

Am I allowed to like add your name with this @ArkaneX -feature whenever I have a question? Cause I have read like 20hours on the X$$anonymous$$L stuff and understood nothing.... I read your answer and I now would say I understand 90% of the entire process of it :)

I dont know what those "Reward user" points are, but I rewarded you with 2of my 6 points cause I dont care about my own points haha.

Thanks you very much again :)

avatar image ArkaneX HydroxTV · Apr 19, 2016 at 09:48 PM 0
Share

You can mention me if you wish, but I suggest not doing it as a general rule. Unity Answers is a great community, and I'm sure you'll get a solution to your problem sooner or later. Especially if you provide a good description of your issue, and show that you actually tried to solve it (e.g. by posting some code). And besides, there are a lot of Unity topics, that I have no clue about, so if you mention me in a question related to such topic, I'll be a bit embarrassed not being able to answer ;)

As to the points - they generally show your reputation here - the more you have, the more you can - like XP in RPG :) $$anonymous$$ore about these points in FAQ, which I suggest to read, if you plan to use this site.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

WebGL XML parsing error "InvalidOperationException" 0 Answers

How can I serialize and deserialize XMLs with special characters? 0 Answers

Read AND Write to XML at runtime 1 Answer

XML Serializer not deserializing past second class 1 Answer

How to Shortly Reset a XML File and Class VariablesTo Create New Game 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges