Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

XML - Reading a XML file in Unity - How to do it?

Discussion in 'Scripting' started by MiLu, Mar 24, 2010.

  1. MiLu

    MiLu

    Joined:
    Feb 18, 2010
    Posts:
    27
    Hey :)

    Im still very new to all this scripting in UNITY. I want to make a dialogue system to a game I work on.

    For me it seems easiest to just make an XML file where I store all the text the dialogue system need to use.

    But where I am stuck is to how I read a XML file inside a unity script and then post it out in like a GUI textbox or similar.

    Can anyone be so kind to tell me how to read from an XML file?

    To store new data into the XML file would be great aswell, but my main concern is to first read from it.
     
    cmq233 likes this.
  2. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    the easiest is likely using System.Xml from .NET itself and providing it with the expected data.
     
  3. matthewminer

    matthewminer

    Joined:
    Aug 29, 2005
    Posts:
    331
    Like dreamora mentioned, System.Xml works great for parsing XML. Note though that this will add considerably to the file size (about a megabyte if I'm not mistaken). If download time is a concern and you need something more lightweight, take a look at the ~7 KB XML parser a forum member wrote.
     
  4. MiLu

    MiLu

    Joined:
    Feb 18, 2010
    Posts:
    27
    Thanks for your replies :)

    And yes I think the System.Xml would work great. If I was using C# which I sadly ain't

    It has been decided that the game shall be made in JavaScript so I am wondering if I can use something similar to System.Xml in JavaScript or does it have a totally other aproach to it then?

    But size and load times aint that big an issue since the game will be build as a standalone application. No web streaming will be made.
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    That makes no difference...System.Xml has nothing to do with C#.

    --Eric
     
  6. MiLu

    MiLu

    Joined:
    Feb 18, 2010
    Posts:
    27
    Doesn't system.xml come from the C# Mono assemblies or?

    Oh well I found a way to import system.xml in javascript and I tried make a test loader which I found some help for on a blog.

    But it gives me some error I cant figure out fully.

    I've made a XML filed called xmltest.xml in a folder I call Resources in my Asset folder. (It looks like this)
    Code (csharp):
    1.  
    2. <?xml version=1.0" encoding=”utf-8" ?>
    3. <system>
    4. <item1 id=1" label=”hello”/>
    5. </system>
    6.  
    And then I have attached this script to my main camera
    Code (csharp):
    1.  
    2. import System.Xml;
    3. import System.IO;
    4.  
    5. function Start()
    6. {
    7.     var asset:TextAsset = Resources.Load("xmltest");
    8.     if(asset != null)
    9.     {
    10.         var reader:XmlTextReader = new XmlTextReader(new StringReader(asset.text));
    11.         while(reader.Read())
    12.         {
    13.             if(reader.Name == "item1")
    14.             {
    15.                 Debug.Log(reader.Name + " label = " + reader.GetAttribute("label"));
    16.             }
    17.         }
    18.     }
    19. }
    20.  
    21. function Update () {
    22. }
    23.  
    But of some reason I cant figure out it gives me this error when I run it.

    ERROR msg:
    XmlException: '"' or ''' is expected. Line 1, position 38.
    Mono.Xml2.XmlTextReader.ParseAttributeFromString (System.String src, System.Int32 idx, System.String name, System.String value)
    Mono.Xml2.XmlTextReader.VerifyXmlDeclaration ()
    Mono.Xml2.XmlTextReader.ReadProcessingInstruction ()
    Mono.Xml2.XmlTextReader.ReadContent ()
    Mono.Xml2.XmlTextReader.Read ()
    System.Xml.XmlTextReader.Read ()
    XML-Reader.Start () (at Assets\XML-Reader.js:10)


    So yeah I am missing something to make it work fully. Any suggestions?
     
  7. MiLu

    MiLu

    Joined:
    Feb 18, 2010
    Posts:
    27
    Ha! See thats weird! When I postet here now I noticed that this forum cant understand all my " characters (in xmltest.xml) so I tried to rewrite them all in the XML document and now it all works!

    Lovely! :D
     
  8. MiLu

    MiLu

    Joined:
    Feb 18, 2010
    Posts:
    27
    Ok... I've now tried to move further from my prototype.

    I have made this XML document

    Code (csharp):
    1.  
    2. <?xml version="1.0" encoding="utf-8" ?>
    3.  
    4. <dialogue>
    5.     <npc1>
    6.         <speach1>Speach bubble 1</speach1>
    7.         <speach2>Speach bubble 2</speach2>
    8.         <speach3>Speach bubble 3</speach3>
    9.     </npc1>
    10. </dialogue>
    11.  
    (This code is made to just try and see how I read the first <speach1> element and then later I will try implant the SPACE funtion to read the next element)

    My script looks like this but i totally wrong I know, but I just cant figure out how to make it.

    Code (csharp):
    1.  
    2. import System.Xml;
    3. import System.IO;
    4.  
    5. var StringToBubble : String;
    6.  
    7. function Start()
    8. {
    9.     var asset:TextAsset = Resources.Load("xmltest");
    10.     if(asset != null)
    11.     {
    12.         var reader:XmlTextReader = new XmlTextReader(new StringReader(asset.text));
    13.         while(reader.Read())
    14.         {
    15.             if(reader.Name == "npc1")
    16.             {              
    17.                 StringToBubble = (reader.Name + reader.ReadChars("speach1"));
    18.             }
    19.         }
    20.     }
    21. }
    22.  
    23. function Update () {
    24. }
    25.  
    26. function OnGUI  ()
    27. {
    28.     GUI.Box (Rect (75, 75, 100, 20), StringToBubble);
    29. }
    30.  

    And I want to start with reading the text in <speach1> and when the player press like for example SPACE it goes to read <speach2>

    BUT for now it is only done so you can read <speach1> and nothing else.

    But it gives me this error:
    Assets/XML-Reader.js(16,81): BCE0017: The best overload for the method 'System.Xml.XmlTextReader.ReadChars((char), int, int)' is not compatible with the argument list '(String)'.


    So I have to type something else in the ReadChars() ?

    I found this on MSDN about ReadChars()
    Code (csharp):
    1.  
    2. public function ReadChars(
    3.     buffer : char[],
    4.     index : int,
    5.     count : int
    6. ) : int
    7.  
    But how to use that IF that is the correct way to read and show large amount of text I dont know.

    Anyone know what I am doing wrong and can show me how to do it correct? :)
     
  9. MiLu

    MiLu

    Joined:
    Feb 18, 2010
    Posts:
    27
    Anyone? :) I would really apreciate if one could take a look at this. I seem to be stuck now.
     
  10. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    The XML classes in .NET are quite complicated. You may find the XML script mentioned earlier by Matthew to be easier to use. It reads the contents of the file directly into a JavaScript array which you can access using the usual indexing.
     
    LexGear likes this.
  11. DaveA

    DaveA

    Joined:
    Apr 15, 2009
    Posts:
    310
    Don't know if you found your answer, but here's what I just knocked out. I needed quick and dirty. I'm parsing a private xml file (via WWW), so no validation is needed or wanted. I know what to expect, if I don't get it, I know it's bad.

    That said, if anyone wants to correct this slop, feel free to post suggestions here. I'm sure it's overkill and bad form and such. Did this via copy/paste from several sources. I dropped this on an empty GameObject, but perhaps using 'static' would be better?
    Code (csharp):
    1.  
    2. import System;
    3. import System.IO;
    4. import System.Xml;
    5. import System.Text;
    6.  
    7. function Start ()
    8. {
    9.   getXMLdata();
    10. }
    11.  
    12. public function getXMLdata ()
    13. {
    14.   var i;
    15. Debug.Log("getting...");
    16.   var url = "http://myserver/myscript";
    17.   // Start a download of the given URL
    18. Debug.Log("...from "+url);
    19.   var www : WWW = new WWW (url);
    20. Debug.Log("yielding");
    21.   // Wait for download to complete
    22.   yield www;
    23. Debug.Log("yielded");
    24.  
    25.   var xml = new XmlDocument();
    26.   xml.LoadXml([url]www.data[/url]);
    27.    
    28.   var wrapperNode = xml.LastChild;
    29.   if (wrapperNode.Name != "wrapper")
    30.   {
    31.     Debug.LogError("This is not a wrapper file");
    32.   }
    33. Debug.Log("got data");
    34.  
    35. /* Example XML:
    36. <wrapper>
    37.  <myData address="123 Main St." desc="Casa de Joe Shmoe">
    38.   <income>0</income>
    39.   <bday>Jun 09,1910</bday>
    40.  </myData>
    41. </wrapper>
    42. */
    43.   var cnodeCount = wrapperNode.ChildNodes.Count;
    44. Debug.Log("got " +cnodeCount);
    45.   for (i = 0; i < cnodeCount; i++)
    46.   {
    47.     var dataNode = wrapperNode.ChildNodes.Item(i);
    48.     var address = dataNode.Attributes["address"].Value;
    49.     var desc = dataNode.Attributes["desc"].Value;
    50.     var cCount = dataNode.ChildNodes.Count;
    51.     var income = "";
    52.     var bday = "";
    53.     for (var j = 0; j < cCount; j++)
    54.     {
    55.       if (dataNode.ChildNodes.Item(j).Name == "income")
    56.         income = dataNode.ChildNodes.Item(j).InnerText;
    57.       else if (dataNode.ChildNodes.Item(j).Name == "bday")
    58.         bday = dataNode.ChildNodes.Item(j).InnerText;
    59.     }
    60. // Now do something useful with this data
    61.   }
    62. }
     
  12. apple_motion

    apple_motion

    Joined:
    Jul 2, 2009
    Posts:
    169
    In fact, everyone seem to be lazy as me, not reading every pages of unity document :p

    Near the bottom of the following page, you will found a small text that mentioned a light weight XML parser that wrote by Novell, the creator of Mono framework. Think that is very reliable too :)
    http://unity3d.com/support/documentation/Manual/Reducing File size.html

    "Reducing included dlls in the Web Player...

    .... If you need to parse some Xml files, you can use a smaller xml library like this one Mono.Xml.zip. While most Generic containers are contained in mscorlib, Stack<> and few others are in System.dll. So you really want to avoid those."
     
  13. gobbledeegeek

    gobbledeegeek

    Joined:
    Dec 3, 2009
    Posts:
    90
    I knocked this up for you....
    I chnged the xml slightly:
    Code (csharp):
    1.  
    2. <?xml version="1.0" encoding="utf-8" ?>
    3. <npcs>
    4.    <npc name="Colin" npcType="Barman" entries="3">
    5.       <speach>Speach bubble 1</speach>
    6.       <speach>Speach bubble 2</speach>
    7.       <speach>Speach bubble 3</speach>
    8.    </npc>
    9. </npcs>
    10.  
    I changed it so you could have multiple npcs in one file but you'd have to use a string to pick the correct npc data to load, and use a load(npcname) function instead of using Start.

    here's the code, with comments :wink:
    Code (csharp):
    1. import System.Xml;
    2.  
    3. // npc data
    4. var npcName : String;
    5. var npcType : String;
    6.  
    7. // chat data
    8. var maxData : int;
    9. var showData : int;
    10. var data : String[];
    11.  
    12. //simple gui to show read data
    13. function OnGUI()
    14. {
    15.     // ensures I don't try to show data I don't have
    16.     if(showData<maxData)
    17.     {
    18.         GUI.Label(Rect(0,0,200,20), npcType+":"+npcName);
    19.         GUI.Label(Rect(0,20,200,100), data[showData]);
    20.         if(GUI.Button(Rect(0,120,200,20),"Next"))
    21.         {
    22.             // goto next
    23.             showData++;
    24.             // wrap
    25.             if(showData>=maxData)
    26.                 showData=0;
    27.         }
    28.     }
    29. }
    30.  
    31. function Start()
    32. {
    33.     // initialise data
    34.     maxData = 0;
    35.     showData = 0;
    36.     npcName = "unset";
    37.     npcName = "unset";
    38.     data = null;
    39.    
    40.     //readxml from chat.xml in project folder (Same folder where Assets and Library are in the Editor)
    41.       var reader:XmlReader = XmlReader.Create("chat.xml");
    42.       //while there is data read it
    43.       while(reader.Read())
    44.       {
    45.         //when you find a npc tag do this
    46.          if(reader.IsStartElement("npc"))
    47.          {
    48.             // get attributes from npc tag
    49.             npcName=reader.GetAttribute("name");
    50.             npcType = reader.GetAttribute("npcType");
    51.             maxData = parseInt(reader.GetAttribute("entries"));
    52.            
    53.             //allocate string pointer array
    54.             data = new String[maxData];
    55.            
    56.             //read speach elements (showdata is used instead of having a new int I reset it later)
    57.             for(showData = 0;showData<maxData;showData++)
    58.             {
    59.                 reader.Read();
    60.                 if(reader.IsStartElement("speach"))
    61.                 {
    62.                     //fill strings
    63.                     data[showData] = reader.ReadString();
    64.                 }
    65.             }
    66.             //reset showData index
    67.             showData=0;
    68.          }
    69.       }
    70.    
    71. }
    72.  
    As it says in the code, it loads the xml from the project folder, so you can change the file and not have to create a new build to view it, and if you add the load function you could edit the file while the build is running, and it'd read the file each time load is called, so you'd see changes as you make them. :wink:

    Also easy to change to a resource if you want it that way.
     
  14. afalk

    afalk

    Joined:
    Jun 21, 2010
    Posts:
    164
    Cool thread - some great resource links and nice ideas!
     
  15. nia1701

    nia1701

    Joined:
    Jun 8, 2012
    Posts:
    74
    Hi guys, I thought this might be a good place to ask this question and the answer might help a lot of people out there....

    Here is my xml:

    Code (csharp):
    1.    
    2. <questions>
    3.       <page id = "1">
    4.         <ask id = "hex">Hex!</ask>
    5.         <ask id = "battery">Battery.</ask>
    6.         <ask id = "exitconv">Exit Conversation</ask>
    7.          </page>
    8.      <page id = "2">   
    9.         <ask id = "tents">Tents</ask>
    10.         <ask id = "marshm">Marshmallows</ask>
    11.         <ask id = "roasting">Roasting Stick</ask>
    12.         <ask id = "engage">Engage in friendly conversation.</ask>
    13.         <ask id = "exitconv">Exit Conversation</ask>
    14.           </page>
    15.      <page id = "3">
    16.         <ask id ="exitconv">Exit Conversation</ask>
    17.      </page>
    18.     </questions>
    19.  

    here is my attempt at using System.xml which doesn't even close to work....

    Code (csharp):
    1.  
    2. function Questions() {
    3.    
    4.     var reader : XmlReader = XmlReader.Create("Assets/AssetFiles/CampScene/CamText.xml");
    5.  
    6.     while (reader.Read())
    7.     {
    8.        
    9.             if(reader.IsStartElement("page")){
    10.                 if (parseInt(reader.GetAttribute("id")) == 1) {
    11.                     reader.ReadStartElement("page");
    12.                     while (reader.Read()) {
    13.                            if (reader.IsStartElement("ask"))
    14.                                                       print(reader.ReadString());
    15.                    
    16.                      }
    17.                    
    18.                    
    19.                 }  
    20.             }
    21.        
    22.     }
    23. }
    24.  
    I'm trying to figure out how to display only questions that are on a specified page by using the attribute "id" i created in the xml to identify which page to grab the questions from. I've poured over the .net instructions and I cannot figure this out! Any ideas? My code displays every "ask" question from the xml instead of just the ones from a certain "page".
    Thanks!
     
  16. UnityCoder

    UnityCoder

    Joined:
    Dec 8, 2011
    Posts:
    534
    here is my perfect working example :
    Code (csharp):
    1. void Start{
    2.         XmlDocument doc = new XmlDocument ();
    3.         doc.Load (UnityEngine.Application.dataPath + "/test.xml");
    4.         XmlNode root = doc.FirstChild;
    5.         for (int i = 0; i < root.SelectNodes("descendant::*").Count; i++) {
    6.             if (root.SelectNodes ("descendant::*") [i].Name.ToString ().ToLower ().Contains ("enddate")) {
    7.                 string tempString = root.SelectNodes ("descendant::*") [i].InnerText;
    8.                 tempString = tempString.Substring (1, 8);
    9.                 string newDate = tempString.Substring (2, 2) + "/";
    10.                 newDate += tempString.Substring (0, 2) + "/";
    11.                 newDate += tempString.Substring (6);
    12.                 DateTime licDate = DateTime.Parse (newDate);
    13.  
    14.                 if (DateTime.Today.Date > licDate.Date) {
    15.                     //MessageBox.Show("Your lic is expired");
    16.                 } else {
    17.                     //UnityEngine.Debug.Log("Your lic is running");
    18.                 }
    19.             }
    20.            
    21.             if (root.SelectNodes ("descendant::*") [i].Name.ToString ().ToLower ().Contains ("coursepackname")) {
    22.                 coursePackName.Add(root.SelectNodes ("descendant::*") [i].InnerXml);
    23. //              print (root.SelectNodes ("descendant::*") [i].InnerXml);
    24.             }
    25.         }  

    And Here is the xml:
    Code (csharp):
    1. <NewDataSet>
    2.   <dtCoursePack>
    3.     <LicenseId>0808201210377141</LicenseId>
    4.     <StartDate>1080820120310</StartDate>
    5.     <EndDate>1150820120310</EndDate>
    6.     <CoursePackName>UNI-100-000-S-HS-1234</CoursePackName>
    7.     <CoursePackDescription>Universal Stereo High Sch</CoursePackDescription>
    8.     <Version>UNI-100-812-ST-HS-1234</Version>
    9.   </dtCoursePack>
    10.   <dtCoursePack>
    11.     <LicenseId>0808201210377141</LicenseId>
    12.     <StartDate>1080820120310</StartDate>
    13.     <EndDate>1150820120310</EndDate>
    14.     <CoursePackName>UNI-100-000-S-MS-1234</CoursePackName>
    15.     <CoursePackDescription>Universal Stereo Middle Sch</CoursePackDescription>
    16.     <Version>UNI-100-812-ST-MS-1234</Version>
    17.   </dtCoursePack>
    18.   <dtCoursePack>
    19.     <LicenseId>0808201210377141</LicenseId>
    20.     <StartDate>1080820120310</StartDate>
    21.     <EndDate>1150820120310</EndDate>
    22.     <CoursePackName>UNI-100-000-S-SS-1234</CoursePackName>
    23.     <CoursePackDescription>Universal Stereo Secondry School</CoursePackDescription>
    24.     <Version>UNI-100-812-ST-SS-1234</Version>
    25.   </dtCoursePack>
    26. </NewDataSet>
     
    QcenzoStudio likes this.
  17. nia1701

    nia1701

    Joined:
    Jun 8, 2012
    Posts:
    74

    here is a solution I came up with if it helps anyone.....
    Code (csharp):
    1.  
    2. var doc : XmlDocument = new XmlDocument();
    3.     doc.Load("Assets/AssetFiles/CampScene/CamText.xml");
    4.    
    5.     var nodeList : XmlNodeList;
    6.     var root : XmlNode = doc.DocumentElement;
    7.    
    8.     nodeList = root.SelectNodes("descendant::page[@id='1']");  //this selects all nodes with page id="1"
    9.    
    10.     nodeList = nodeList[0].ChildNodes;  //this rebuilds the list using all the childnodes from the nodes with page id ="1"
    11.    
    12.        
    13.     var i : int;
    14.     for (i=0; i<nodeList.Count; i++) {
    15.         print(nodeList[i].Attributes["id"].Value);  
    16.         print(nodeList[i].InnerText);  
    17.        
    18.     }
    19.  
     
  18. PauloPeresJr

    PauloPeresJr

    Joined:
    Sep 24, 2012
    Posts:
    1
    Stoping with the difficult code.
    I coded my XML this way and work perfect

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Xml;
    4. using System.IO;
    5.  
    6. public class Interface : MonoBehaviour {
    7.    
    8.     // Use this for initialization
    9.    
    10.     void Start ()
    11.     {
    12.        
    13.         var xml = new XmlDocument();
    14.         if (Application.systemLanguage.ToString() == "Portuguese"){
    15.             xml.Load(UnityEngine.Application.dataPath + "/XMLS/PT-BR.xml");
    16.         }else{
    17.             xml.Load(UnityEngine.Application.dataPath + "/XMLS/EN.xml");
    18.         }
    19.         print (xml.ChildNodes[0].ChildNodes[1].InnerText);
    20.        
    21.        
    22.        
    23.     }
    24.    
    25.    
    26.     // Update is called once per frame
    27.     void Update () {
    28.    
    29.     }
    30. }
    31.  
     
  19. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Unity Community - Y U No Use Serialization

    Code (csharp):
    1.  
    2. using System.Xml.Serialization;
    3.  
    4. namespace Kelso.UnityForum
    5. {
    6.     [XmlRoot(ElementName = "questions")]
    7.     public class Questions
    8.     {
    9.         [XmlElement(ElementName = "page")]
    10.         public Page[] Pages { get; set; }
    11.     }
    12.    
    13.     public class Page
    14.     {
    15.         [XmlAttribute(AttributeName = "id")]
    16.         public int Id { get; set; }
    17.    
    18.         [XmlElement(ElementName = "ask")]
    19.         public Ask[] Asks { get; set; }
    20.     }
    21.    
    22.     public class Ask
    23.     {
    24.         [XmlAttribute(AttributeName = "id")]
    25.         public string Id { get; set; }
    26.        
    27.         [XmlText(Type = typeof(string))]
    28.         public string Value { get; set; }
    29.     }
    30. }
    31.  
    Code (csharp):
    1.  
    2. using System;
    3. using System.IO;
    4. using System.Xml.Serialization;
    5. using UnityEngine;
    6. using Kelso.UnityForum;
    7.  
    8. public class Loader : MonoBehaviour
    9. {
    10.     private Questions questions;
    11.    
    12.     void Start()
    13.     {
    14.         XmlSerializer serial = new XmlSerializer(typeof(Questions))]
    15.         Stream reader = new FileStream("test.xml", FileMode.Open);
    16.         questions = (Questions)serial.Deserialize(reader);
    17.     }
    18. }
    19.  
     
    MINhxxx, Sistance and Mintonne like this.
  20. HolBol

    HolBol

    Joined:
    Feb 9, 2010
    Posts:
    2,887
    Just wondering how you'd implement the above into a working dialogue system- how you'd call the relevant questions when needed?
     
  21. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Depends on what your data structure looks like and how your dialogue works. I'd probably give everything an ID and then the responses can reference which ID they should "trigger" if picked. Off the top of my head - something like this:
    Code (csharp):
    1.  
    2. <dialogue>
    3.     <question id="1">
    4.         <text>How are you?</text>
    5.         <responses>
    6.             <response triggerId="2">Fine.  How are you?</response>
    7.             <response triggerId="3">None of your business!</response>
    8.         </responses>
    9.     </question>
    10.     <question id="2">
    11.         <text>Fantastic!</text>
    12.     </question>
    13.     <question id="3">
    14.         <text>Fine!  Piss off then!</text>
    15.     </question>
    16. </dialogue>
    17.  
    Code (csharp):
    1.  
    2. using System.Xml.Serialization;
    3.  
    4. [XmlRoot("dialogue")]
    5. public class Dialogue
    6. {
    7.     [XmlElement("question")]
    8.     public Question[] Questions { get; set; }
    9. }
    10.  
    11. public class Question
    12. {
    13.     [XmlAttribute("id")]
    14.     public int Id { get; set; }
    15.    
    16.     [XmlElement("text")]
    17.     public string Text { get; set; }
    18.    
    19.     [XmlArray("responses")]
    20.     [XmlArrayItem("response")]
    21.     public Response[] Responses { get; set; }
    22. }
    23.  
    24. public class Response
    25. {
    26.     [XmlAttribute("triggerId")]
    27.     public int NextQuestion { get; set; }
    28.  
    29.     [XmlElement("text")]
    30.     public string Text { get; set; }
    31. }
    32.  
     
    Last edited: Mar 15, 2013
    wcc likes this.
  22. sathyaarun

    sathyaarun

    Joined:
    Dec 7, 2012
    Posts:
    1
    this is my database code to get request and responce from url. i want to put this reply in speech bubble please help me with the code for parsing and putting in speech bubble.... :(
    private DB db;
    WWW results;
    void Start ()
    {
    db = GameObject.Find("DB").GetComponentInChildren<DB>();
    results = db.GET("http://www.pandorabots.com/pandora/talk?botid=9d51442b5e34558e");
    Debug.Log(results.text);
    }

    // Update is called once per frame
    void Update () {

    }

    public WWW GET(string url)
    {

    WWW www = new WWW (url);
    StartCoroutine (WaitForRequest (www));
    return www;
    }

    public WWW POST(string url, Dictionary<string,string> post)
    {
    WWWForm form = new WWWForm();
    foreach(KeyValuePair<String,String> post_arg in post)
    {
    form.AddField(post_arg.Key, post_arg.Value);
    }
    WWW www = new WWW(url, form);

    StartCoroutine(WaitForRequest(www));
    return www;
    }

    private IEnumerator WaitForRequest(WWW www)
    {
    yield return www;

    // check for errors
    if (www.error == null)
    {
    Debug.Log("WWW Ok!: " + www.text);

    } else {
    Debug.Log("WWW Error: "+ www.error);
    }
    if (www.text != null)
    {
    print (results);
    }
    }
    }
     
  23. UKSSL

    UKSSL

    Joined:
    May 30, 2013
    Posts:
    1
    your code doesnt seem to work for me I keep running into the following error --
    any ideas?

    EDIT:just wanted to add this error crops up on running the game not during compile.
     
    Last edited: Feb 28, 2014
  24. Ben-BearFish

    Ben-BearFish

    Joined:
    Sep 6, 2011
    Posts:
    1,204
    @KelsoMRK With regards to this implementation. I'm trying to do the same thing, but also trying to combine my objects into a web.config file, so I'm getting an error when Deserializing. Do you know of a way to deserialize something like that?

    Example XML FILE:
    Code (csharp):
    1.  
    2. <?xmlversion="1.0"encoding="utf-8"?>
    3.     <configuration>
    4.          <system.webServer>
    5.          <staticContent>
    6.                   <mimeMapfileExtension=".unity3d"mimeType="application/vnd.unity" />
    7.          </staticContent>
    8.          <httpProtocol>
    9.          <customHeaders>
    10.                   <!-- Enable Cross Domain AJAX calls -->
    11.                   <removename="Access-Control-Allow-Origin" />
    12.                   <addname="Access-Control-Allow-Origin"value="*" />
    13.          </customHeaders>
    14.          </httpProtocol>
    15.          </system.webServer>
    16.  
    17.          <WebApiConfig>
    18.                   <WebApiUrl>www.website.com</WebApiUrl>
    19.                   <BlobUrl>www.blob.com</BlobUrl>
    20.                   <GetFileByIDUrl>Api/Files/</GetFileByIDUrl>
    21.          </WebApiConfig>
    22. </configuration>
    23.  
    Example Object:
    Code (csharp):
    1. public class WebApiConfig
    2. {
    3.          public WebApiConfig() { }
    4.  
    5.          [XmlElement("WebApiUrl")]
    6.          public string WebApiUrl { get; set; }
    7.  
    8.          [XmlElement("BlobUrl")]
    9.          public string BlobUrl { get; set; }
    10.  
    11.          [XmlElement("GetFileByIDUrl")]
    12.          public string GetFileByIDUrl { get; set; }
    13.  
    14.          public static WebApiConfig LoadFromText(string text)
    15.          {
    16.                   var serializer = new XmlSerializer(typeof(WebApiConfig));
    17.                   return serializer.Deserialize(new StringReader(text)) as WebApiConfig;
    18.          }
    19. }
     
  25. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    You can't deserialize just a piece of a file like that. It's expecting <WebApiConfig> to be the root of your document. One solution would be to read the contents of the file and extract the part you need as a string and then deserialize just that string.
     
  26. Aryal007

    Aryal007

    Joined:
    Feb 3, 2016
    Posts:
    2
    how many entries can one xml file take in unity.
    i have to add around 1000 lines but unity is getting slow as well as it is taking time to load the questions i have added in my xml.
    so wat is the easiest solution???
    And it is not loading my xml file when i am using the the reader variable.
     
  27. Aryal007

    Aryal007

    Joined:
    Feb 3, 2016
    Posts:
    2
    <Question>
    <Body1 questionText1 ="What is the capital city of France?" answerA1="London" answerB1="Paris" answerC1="Leon" answerD1="Baguette"/>

    How can i print this in console???
     
  28. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    A lot. It isn't a Unity-specific function so the answer would be the same for any .NET app.
    We do more than that and it's fine. Are you loading it just once or over and over again?
    I don't understand the question
     
    Mintonne likes this.
  29. Mintonne

    Mintonne

    Joined:
    Aug 7, 2015
    Posts:
    306
    Hey guys. Came across this and thought i should share my method. I modified KelsoMRK method slightly.

    My XML File
    Code (CSharp):
    1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    2. <QuestionDatabase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    3.     <Questions>
    4.         <Question>Name the manufacterer of the car in the picture?</Question>
    5.         <Image>Ava</Image>
    6.         <Answers>
    7.             <Choices correct="true">Lamborghini</Choices>
    8.             <Choices correct="false">Ferrari</Choices>
    9.             <Choices correct="false">Tesla</Choices>
    10.             <Choices correct="false">Porsche</Choices>
    11.         </Answers>
    12.     </Questions>
    13.     <Questions>
    14.         <Question>Kanye West owns what shoe brand?</Question>
    15.         <Image></Image>
    16.         <Answers>
    17.             <Choices correct="false">Nike</Choices>
    18.             <Choices correct="false">Adidas</Choices>
    19.             <Choices correct="true">Yeezys</Choices>
    20.             <Choices correct="false">Fubu</Choices>
    21.         </Answers>
    22.     </Questions>
    23. </QuestionDatabase>

    I need to parse this info to a List<T>

    This is my 'main' class script

    Code (CSharp):
    1. [Serializable]
    2. public class QuizApp{
    3.  
    4.     [XmlElement("Question")]
    5.     public string question;
    6.  
    7.     [XmlArray("Answers")]
    8.     [XmlArrayItem("Choices")]
    9.     public Answers[] Answer;
    10.  
    11.     [XmlElement("Image")]
    12.     public string Image;
    13. }
    The script above also relies on this class too.
    Code (CSharp):
    1. [Serializable]
    2. public class Answers{
    3.    
    4.     public string Choices;
    5.  
    6.     [XmlAttribute("correct")]
    7.     public bool Correct;
    8. }


    I use this script to deserialize



    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Xml.Serialization;
    5. using System.IO;
    6.  
    7. [XmlRoot("QuestionDatabase")]
    8. public class QuizAppContainer {
    9.  
    10.     [XmlElement("Questions")]
    11.     public List<QuizApp> Quizes = new List<QuizApp>();
    12.  
    13.     public static QuizAppContainer Load(string path)
    14.     {
    15.         TextAsset _xml = Resources.Load<TextAsset>(path);
    16.  
    17.         XmlSerializer serializer = new XmlSerializer(typeof(QuizAppContainer));
    18.  
    19.         StringReader reader = new StringReader(_xml.text);
    20.  
    21.         QuizAppContainer Items = serializer.Deserialize(reader) as QuizAppContainer;
    22.  
    23.         reader.Close();
    24.  
    25.         return Items;
    26.     }
    27. }


    And the final step is to copy the info into my List<T>

    Code (CSharp):
    1.  
    2.     public List<QuizApp> Questions;
    3.    
    4.     //Load the question from the xml to the questions array
    5.     IEnumerator LoadQuestions(string category)
    6.     {
    7.         //load the questions from the XML
    8.         QuizAppContainer ic = QuizAppContainer.Load(category);
    9.  
    10.         //Clear List<QuizApp> contents
    11.         if(Questions.Count>0) Questions.Clear();
    12.  
    13.         //Parse the questions from the XML file to the list
    14.         foreach (QuizApp item in ic.Quizes)
    15.             Questions.Add(item);
    16.  
    17.         yield return new WaitForSeconds(1);
    18.  
    19. //        //Initialize new game
    20.  
    21.     }


    This worked for me. However, i had issues deserealizing the answers. I played with the code for hours trying to figure it out and this worked finally (5 hours and 3 naps later :mad::mad::mad:).

    Code (CSharp):
    1.     public string Choices;



    And sorry if i used wrong terminologies to describe stuff.... Still learning.:):)
    Hope this helps someone.
     
  30. Mintonne

    Mintonne

    Joined:
    Aug 7, 2015
    Posts:
    306
    The code snippets are thoroughly tested and i am using them in my Unity Asset Store Ultimate Trivia template. I am extensively using XML files and i have tested it with about 2300 questions and it worked fine on mobile. It can be a perfect learning tool. You can get it from here
    PS. The current version on Unity Asset store says True or False trivia template. Currently working on a major update to make it a full trivia template (Think QuizUp orTriviaCrack) with a whole lot of awesome stuff. Should be done by early April.

    Sorry for sounding sales-y but it was just in case someone was in doubt.
     
  31. TroyDavis

    TroyDavis

    Joined:
    Mar 27, 2013
    Posts:
    78
    I use mine to save and backup an item database for my game.
    I start with a couple of preperation files
    Code (csharp):
    1.  
    2.        #region XML Preperation
    3.  
    4.         public void writeToXML(XmlWriter _w)
    5.         {
    6.             _w.WriteStartElement("Item");
    7.             _w.WriteAttributeString("Name", _name);
    8.             _w.WriteAttributeString("ItemType", ((int)_itemType).ToString());
    9.             _w.WriteAttributeString("UniqueID", _uniqueID.ToString());                                  
    10.             _w.WriteAttributeString("Description", _description);
    11.             _w.WriteAttributeString("VendorPrice", _vendorPrice.ToString());
    12.             _w.WriteAttributeString("Icon", AssetDatabase.GetAssetPath(_icon));
    13.             _w.WriteAttributeString("Prefab", AssetDatabase.GetAssetPath(_prefab));
    14.             _w.WriteAttributeString("Moddable", _moddable.ToString());
    15.             _w.WriteAttributeString("PrimaryWeapon", _primaryWeapon.ToString());
    16.             _w.WriteAttributeString("RecoilCompensation", _RecoilCompensation.ToString());
    17.             _w.WriteAttributeString("Semi-Auto", _allowedFireModes[0].ToString());
    18.             _w.WriteAttributeString("Burst", _allowedFireModes[1].ToString());
    19.             _w.WriteAttributeString("Full-Auto", _allowedFireModes[2].ToString());
    20.             _w.WriteAttributeString("AttributeBars", _attributeBars.ToString());
    21.             _w.WriteAttributeString("AmmoType", ((int)_ammoType).ToString());
    22.             _w.WriteAttributeString("AmmoAttribute", ((int)_ammoAttribute).ToString());
    23.             _w.WriteAttributeString("ClipCapacity", _clipCapacity.ToString());
    24.             _w.WriteAttributeString("AmmoDamage", _ammoDamage.ToString());
    25.             _w.WriteAttributeString("ModItemType", ((int)_modItemType).ToString());
    26.             _w.WriteAttributeString("MagnificationValue", _magnificationValue.ToString());
    27.             _w.WriteAttributeString("SupressionValue", _recoilReductionValue.ToString());
    28.             _w.WriteAttributeString("SilencingValue", _silencingValue.ToString());
    29.             _w.WriteAttributeString("RetinalLinkValue", _retinalLinkValue.ToString());
    30.             _w.WriteAttributeString("IsStackable", _isStackable.ToString());
    31.             _w.WriteAttributeString("DamageAbsorptionValue", _damageAbsorptionValue.ToString());
    32.             _w.WriteAttributeString("PenetrationNegationValue", _penetrationNegationValue.ToString());
    33.             _w.WriteAttributeString("EquipmentSlot", ((int)_equipmentSlot).ToString());
    34.             _w.WriteAttributeString("ConsumableType", ((int)_consumableType).ToString());
    35.             _w.WriteAttributeString("HealthRestorationAmount", _healthRestorationAmount.ToString());
    36.             _w.WriteAttributeString("AttributeName", ((int)_attributeName).ToString());
    37.             _w.WriteAttributeString("AttributeBuffAmount", _attributeBuffAmount.ToString());
    38.             _w.WriteAttributeString("AmmoCompatibilityTags", _ammoCompatabilityTags.ToString());
    39.             _w.WriteAttributeString("WeaponModCompatibilityTags", _weaponModCompatabilityTags.ToString());
    40.  
    41.             _w.WriteEndElement();
    42.         }
    43.  
    44.         public void readFromXML(XmlElement _e)
    45.         {
    46.             _itemType = (ISObjectType)int.Parse(_e.GetAttribute("ItemType"));
    47.  
    48.             _name = _e.GetAttribute("Name");
    49.             _uniqueID = _e.GetAttribute("UniqueID");          
    50.             _description = _e.GetAttribute("Description");
    51.             _vendorPrice = int.Parse(_e.GetAttribute("VendorPrice"));
    52.             _icon = AssetDatabase.LoadAssetAtPath<Sprite>(_e.GetAttribute("Icon"));
    53.             _prefab = AssetDatabase.LoadAssetAtPath<GameObject>(_e.GetAttribute("Prefab"));
    54.             _moddable = bool.Parse(_e.GetAttribute("Moddable"));
    55.             _primaryWeapon = bool.Parse(_e.GetAttribute("PrimaryWeapon"));
    56.             _RecoilCompensation = float.Parse(_e.GetAttribute("RecoilCompensation"));
    57.             _allowedFireModes[0] = bool.Parse(_e.GetAttribute("Semi-Auto"));
    58.             _allowedFireModes[1] = bool.Parse(_e.GetAttribute("Burst"));
    59.             _allowedFireModes[2] = bool.Parse(_e.GetAttribute("Full-Auto"));
    60.             _attributeBars = bool.Parse(_e.GetAttribute("AttributeBars"));
    61.             _ammoType = (AmmoTypeEnum)int.Parse(_e.GetAttribute("AmmoType"));
    62.             _ammoAttribute = (AmmoAttributesEnum)int.Parse(_e.GetAttribute("AmmoAttribute"));
    63.             _clipCapacity = int.Parse(_e.GetAttribute("ClipCapacity"));
    64.             _ammoDamage = float.Parse(_e.GetAttribute("AmmoDamage"));
    65.             _modItemType = (ModItemTypeEnum)int.Parse(_e.GetAttribute("ModItemType"));
    66.             _magnificationValue = float.Parse(_e.GetAttribute("MagnificationValue"));
    67.             _recoilReductionValue = float.Parse(_e.GetAttribute("SupressionValue"));
    68.             _silencingValue = float.Parse(_e.GetAttribute("SilencingValue"));
    69.             _retinalLinkValue = float.Parse(_e.GetAttribute("RetinalLinkValue"));
    70.             _isStackable = bool.Parse(_e.GetAttribute("IsStackable"));
    71.             _damageAbsorptionValue = float.Parse(_e.GetAttribute("DamageAbsorptionValue"));
    72.             _penetrationNegationValue = float.Parse(_e.GetAttribute("PenetrationNegationValue"));
    73.             _equipmentSlot = (EquipmentSlot)int.Parse(_e.GetAttribute("EquipmentSlot"));
    74.             _consumableType = (ConsumableTypeEnum)int.Parse(_e.GetAttribute("ConsumableType"));
    75.             _healthRestorationAmount = float.Parse(_e.GetAttribute("HealthRestorationAmount"));
    76.             _attributeName = (AttributeNameEnum)int.Parse(_e.GetAttribute("AttributeName"));
    77.             _attributeBuffAmount = int.Parse(_e.GetAttribute("AttributeBuffAmount"));
    78.             _ammoCompatabilityTags = int.Parse(_e.GetAttribute("AmmoCompatibilityTags"));
    79.             _weaponModCompatabilityTags = int.Parse(_e.GetAttribute("WeaponModCompatibilityTags"));
    80.         }
    81.  
    82.         #endregion
    83.  
    84. #endif
    Then In my custom editor script I have these for when you select the load or save xml buttons:
    Code (csharp):
    1.  
    2.         #region XML Functions
    3.  
    4.         void saveToXML()
    5.         {            
    6.             string path = EditorUtility.SaveFilePanel("Save the database to XML file.", "", "ItemDatabase.xml", ".xml");            
    7.  
    8.             if (path == "")
    9.                 return;
    10.            
    11.             XmlWriterSettings settings = new XmlWriterSettings();
    12.             settings.Indent = true;
    13.             XmlWriter writer = XmlWriter.Create(path, settings);
    14.             writer.WriteStartDocument();
    15.             writer.WriteStartElement("ItemDatabase");
    16.             writer.WriteAttributeString("version", saveXMLVersion.ToString());
    17.  
    18.             for (int i = 0; i < database.Count; i++)
    19.             {
    20.                 database.Get(i).writeToXML(writer);
    21.             }
    22.  
    23.             writer.WriteEndElement();
    24.             writer.WriteEndDocument();
    25.             writer.Flush();
    26.             writer.Close();
    27.         }
    28.  
    29.         void loadFromXML()
    30.         {
    31.             string path = EditorUtility.OpenFilePanel("Select the XML file to load the database from", "", "xml");
    32.  
    33.             if (path == "")
    34.                 return;
    35.  
    36.             XmlDocument doc = new XmlDocument();
    37.             try
    38.             {
    39.                 doc.Load(path);
    40.                 XmlElement root = (XmlElement)doc.GetElementsByTagName("ItemDatabase").Item(0);
    41.                 XmlNodeList xl = root.GetElementsByTagName("Item");
    42.                 database.Clear();
    43.  
    44.                 foreach (XmlElement e in xl)
    45.                 {
    46.                     ISObject obj = new ISObject();
    47.                     obj.readFromXML(e);
    48.                     database.Add(obj);
    49.                 }
    50.  
    51.                 GenerateWeaponTags();
    52.                 AssetDatabase.SaveAssets();
    53.             }
    54.             catch (Exception e)
    55.             {
    56.                 Debug.LogException(e);
    57.             }
    58.         }
    59.  
    60.         #endregion
    This is my output:
    Code (csharp):
    1.  
    2. <?xml version="1.0" encoding="utf-8"?>
    3. <ItemDatabase version="1">
    4.   <Item Name="GA-537" ItemType="2" UniqueID="982597959" Description="Standard Issue Assault Rifle used by the Plantary Defense Forces" VendorPrice="1500" Icon="Assets/Textures/Inventory Icons/GA537.png" Prefab="Assets/Models/GA-537/Prefab/GA-537_prefab.prefab" Moddable="True" PrimaryWeapon="True" RecoilCompensation="10" Semi-Auto="True" Burst="True" Full-Auto="True" AttributeBars="True" AmmoType="2" AmmoAttribute="4" ClipCapacity="0" AmmoDamage="0" ModItemType="4" MagnificationValue="0" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="False" DamageAbsorptionValue="0" PenetrationNegationValue="0" EquipmentSlot="5" ConsumableType="2" HealthRestorationAmount="0" AttributeName="6" AttributeBuffAmount="0" AmmoCompatibilityTags="0" WeaponModCompatibilityTags="0" />
    5.   <Item Name="GA-537 Ammo (%/150)" ItemType="5" UniqueID="468086237" Description="Ammo for GA-537 with % rounds left" VendorPrice="450" Icon="Assets/Textures/GameMenus/InGameMenu/ammo.png" Prefab="Assets/Prefabs/WeaponAccessories/AmmoClips/GA_A_100_AmmoClip.prefab" Moddable="False" PrimaryWeapon="False" RecoilCompensation="0" Semi-Auto="False" Burst="False" Full-Auto="False" AttributeBars="True" AmmoType="0" AmmoAttribute="0" ClipCapacity="150" AmmoDamage="10" ModItemType="4" MagnificationValue="0" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="True" DamageAbsorptionValue="0" PenetrationNegationValue="0" EquipmentSlot="7" ConsumableType="2" HealthRestorationAmount="0" AttributeName="6" AttributeBuffAmount="0" AmmoCompatibilityTags="3" WeaponModCompatibilityTags="0" />
    6.   <Item Name="Medium PDF Infiltration Chest" ItemType="0" UniqueID="576886781" Description="Medium strength Armor worn by PDF Stealth Troopers" VendorPrice="500" Icon="Assets/Resources/A_Chest01.png" Prefab="Assets/Models/AmmoCan/Prefab/AmmoCans.prefab" Moddable="False" PrimaryWeapon="False" RecoilCompensation="0" Semi-Auto="False" Burst="False" Full-Auto="False" AttributeBars="False" AmmoType="2" AmmoAttribute="4" ClipCapacity="0" AmmoDamage="0" ModItemType="4" MagnificationValue="0" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="False" DamageAbsorptionValue="20" PenetrationNegationValue="0" EquipmentSlot="0" ConsumableType="2" HealthRestorationAmount="0" AttributeName="6" AttributeBuffAmount="0" AmmoCompatibilityTags="0" WeaponModCompatibilityTags="0" />
    7.   <Item Name="Aeris SAS Magnum Scope" ItemType="3" UniqueID="818221238" Description="Mountable scope providing 40x magnification" VendorPrice="5000" Icon="Assets/Textures/Inventory Icons/scope.png" Prefab="Assets/Prefabs/WeaponAccessories/AmmoClips/GA_A_100_AmmoClip.prefab" Moddable="False" PrimaryWeapon="False" RecoilCompensation="0" Semi-Auto="False" Burst="False" Full-Auto="False" AttributeBars="True" AmmoType="2" AmmoAttribute="4" ClipCapacity="0" AmmoDamage="0" ModItemType="0" MagnificationValue="40" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="False" DamageAbsorptionValue="0" PenetrationNegationValue="0" EquipmentSlot="7" ConsumableType="2" HealthRestorationAmount="0" AttributeName="6" AttributeBuffAmount="0" AmmoCompatibilityTags="0" WeaponModCompatibilityTags="1" />
    8.   <Item Name="Basic Field First Aid Kit" ItemType="4" UniqueID="932754234" Description="Restores a moderate amount of damage to the user" VendorPrice="1500" Icon="Assets/Textures/Inventory Icons/Syringe.png" Prefab="Assets/Prefabs/WeaponAccessories/AmmoClips/GA_A_100_AmmoClip.prefab" Moddable="False" PrimaryWeapon="False" RecoilCompensation="0" Semi-Auto="False" Burst="False" Full-Auto="False" AttributeBars="True" AmmoType="2" AmmoAttribute="4" ClipCapacity="0" AmmoDamage="0" ModItemType="4" MagnificationValue="0" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="True" DamageAbsorptionValue="0" PenetrationNegationValue="0" EquipmentSlot="7" ConsumableType="0" HealthRestorationAmount="15" AttributeName="6" AttributeBuffAmount="0" AmmoCompatibilityTags="0" WeaponModCompatibilityTags="0" />
    9.   <Item Name="Adrenal Injection" ItemType="4" UniqueID="031748298" Description="Augments the users reflexes for a short amount of time." VendorPrice="0" Icon="Assets/Textures/Inventory Icons/Syringe.png" Prefab="Assets/Prefabs/WeaponAccessories/AmmoClips/GA_A_100_AmmoClip.prefab" Moddable="False" PrimaryWeapon="False" RecoilCompensation="0" Semi-Auto="False" Burst="False" Full-Auto="False" AttributeBars="True" AmmoType="2" AmmoAttribute="4" ClipCapacity="0" AmmoDamage="0" ModItemType="4" MagnificationValue="0" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="True" DamageAbsorptionValue="0" PenetrationNegationValue="0" EquipmentSlot="7" ConsumableType="1" HealthRestorationAmount="0" AttributeName="0" AttributeBuffAmount="5" AmmoCompatibilityTags="0" WeaponModCompatibilityTags="0" />
    10.   <Item Name="GP-9M" ItemType="2" UniqueID="211315174" Description="Modified 9mm hand gun." VendorPrice="1000" Icon="Assets/Textures/Inventory Icons/GP9.png" Prefab="Assets/Prefabs/Weapons/Mason's PeaceMaker/Mason's PeaceMaker.prefab" Moddable="True" PrimaryWeapon="False" RecoilCompensation="10" Semi-Auto="True" Burst="True" Full-Auto="False" AttributeBars="True" AmmoType="2" AmmoAttribute="4" ClipCapacity="0" AmmoDamage="0" ModItemType="4" MagnificationValue="0" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="False" DamageAbsorptionValue="0" PenetrationNegationValue="0" EquipmentSlot="6" ConsumableType="2" HealthRestorationAmount="0" AttributeName="6" AttributeBuffAmount="0" AmmoCompatibilityTags="0" WeaponModCompatibilityTags="0" />
    11.   <Item Name="Aeris Standard Scope" ItemType="3" UniqueID="402888971" Description="Provide 20x magnification" VendorPrice="350" Icon="Assets/Textures/Inventory Icons/scope.png" Prefab="Assets/Prefabs/WeaponAccessories/AmmoClips/GA_A_100_AmmoClip.prefab" Moddable="False" PrimaryWeapon="False" RecoilCompensation="0" Semi-Auto="False" Burst="False" Full-Auto="False" AttributeBars="True" AmmoType="2" AmmoAttribute="4" ClipCapacity="0" AmmoDamage="0" ModItemType="0" MagnificationValue="20" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="False" DamageAbsorptionValue="0" PenetrationNegationValue="0" EquipmentSlot="7" ConsumableType="2" HealthRestorationAmount="0" AttributeName="6" AttributeBuffAmount="0" AmmoCompatibilityTags="0" WeaponModCompatibilityTags="-1" />
    12.   <Item Name="M9A3 Berreta" ItemType="2" UniqueID="619240597" Description="standard 9mm hand gun." VendorPrice="400" Icon="Assets/Textures/Inventory Icons/GP9.png" Prefab="Assets/Military_Pistol_01_Free_v2/FBX/1911_Pistol_01.fbx" Moddable="True" PrimaryWeapon="False" RecoilCompensation="0" Semi-Auto="True" Burst="False" Full-Auto="False" AttributeBars="True" AmmoType="2" AmmoAttribute="4" ClipCapacity="0" AmmoDamage="0" ModItemType="4" MagnificationValue="0" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="False" DamageAbsorptionValue="0" PenetrationNegationValue="0" EquipmentSlot="6" ConsumableType="2" HealthRestorationAmount="0" AttributeName="6" AttributeBuffAmount="0" AmmoCompatibilityTags="0" WeaponModCompatibilityTags="0" />
    13.   <Item Name="M9A3 Standard Ammo (%/10)" ItemType="5" UniqueID="849975363" Description="Standard 9mm hand gun." VendorPrice="3" Icon="Assets/Textures/GameMenus/InGameMenu/ammo.png" Prefab="Assets/Prefabs/WeaponAccessories/AmmoClips/GA_A_100_AmmoClip.prefab" Moddable="False" PrimaryWeapon="False" RecoilCompensation="0" Semi-Auto="False" Burst="False" Full-Auto="False" AttributeBars="True" AmmoType="0" AmmoAttribute="0" ClipCapacity="10" AmmoDamage="2.5" ModItemType="4" MagnificationValue="0" SupressionValue="0" SilencingValue="0" RetinalLinkValue="0" IsStackable="True" DamageAbsorptionValue="0" PenetrationNegationValue="0" EquipmentSlot="7" ConsumableType="2" HealthRestorationAmount="0" AttributeName="6" AttributeBuffAmount="0" AmmoCompatibilityTags="4" WeaponModCompatibilityTags="0" />
    14. </ItemDatabase>
    15.  
     
  32. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    QuizDatabase.Quizes is already a list of questions; why do you put them in another list?
     
    Mintonne likes this.
  33. Mintonne

    Mintonne

    Joined:
    Aug 7, 2015
    Posts:
    306
    Is it possible to access all the xml content and display them on Unity UI? I personally didn't think it was possible.
     
  34. Mintonne

    Mintonne

    Joined:
    Aug 7, 2015
    Posts:
    306
    i think I get what you are saying now. The script i am using to deserialize the xml is unnecessary. i can do it straight from my controller script (the final script)

    I get it now :):)
    I would never have noticed that. Thanks
     
  35. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    That's not what I meant.

    QuizDatabase.Quizes is a list of questions. So your goal of "deserialize into a list of questions" has already been achieved which means lines 14-15 in your LoadQuestions method are just taking the items from one list and putting them into another one. Why are you doing that?
     
  36. Mintonne

    Mintonne

    Joined:
    Aug 7, 2015
    Posts:
    306
    So how can access that list? It is in a different script from the one i am using to display the questions on my ui
     
  37. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    That gets outside the scope of this thread as it has more to do with cross-script communication, of which there is a lot of reading out there - both on this forum and otherwise. It ultimately boils down to how your project is constructed. I just wanted to point out that you were duplicating your effort and ideally the data should be a single location.
     
  38. Mintonne

    Mintonne

    Joined:
    Aug 7, 2015
    Posts:
    306
    Okay. Let me do some research.