Unity How to Format Text File to Be Read in as a Dictionary
I recently started working on a project in Unity 3D that makes utilize of an XML file to load data into the game. Being relatively new to game design, I had to practise a lot of research to figure out how to load the XML file and assign that data in a usable way. I have gotten things working in the game and thought I would write a mail service that details how to read XML information and use it in Unity using C#. What I will comprehend is how to read the information from XML using C# and how to assign that information to a List then that it can be used elsewhere in your program. This is, essentially, the very basics of reading an XML file in Unity.
Options for Reading an XML file in Unity
The kickoff thing I want to indicate out is that in that location are several different ways that this tin can exist accomplished.
XMLReader Course: A lot of people have recommended using the XMLReader course, which provides noncached, forward-simply access to XML data. From what I take read, this is the depression-cost fashion of grabbing XML data. Information technology provides the lowest performance hit in your program.
XMLDocument Form: In that location is also the XMLDocument Class. I know very little well-nigh this form and I ran into very few people advocating for its use within Unity3D.
XDocument Grade: Lastly, there is the XDocument class, which is what I ended up using and what I volition exist using in this mail. Admittedly, I primarily chose information technology because it seemed to be the about well-documented in the Unity realm. In the hereafter, I hope to explore the XMLReader option more than thoroughly since it is considered the most performance-efficient.
STEP 1 – Create XML File
Kickoff of all, you need to have an XML file in your Unity project. You can use a program like Notepad++ to create XML files. Here are the contents of a examination file I am using. Yous tin can copy and paste it into your XML editor and save the file if you lot want:
<?xml version="ane.0″ encoding="UTF-8″ standalone="yes"?>
<chapter_1 xmlns:xsi="http://world wide web.w3.org/2001/XMLSchema-case">
<folio number = "ane">
<proper name>Mark</name>
<dialogue>This is a test!</dialogue>
</folio>
<page number = "2">
<name>Tony</proper noun>
<dialogue>This is a 2nd test.</dialogue>
</folio>
<folio number = "3">
<name>Ballad</name>
<dialogue>This is a 3rd test.</dialogue>
</page>
<page number = "iv">
<proper noun>Kristie</name>
<dialogue>This is a fourth test.</dialogue>
</folio>
<page number = "5">
<name>Jeff</proper noun>
<dialogue>This is a fifth test.</dialogue>
</page>
<folio number = "vi">
<name>Frank</name>
<dialogue>This is a sixth examination.</dialogue>
</folio> </chapter_1>
Footstep two – Add together XML file to Unity
Once yous accept the file created, you will demand to put it somewhere in your Unity project. I put mine within Avails/Resources/XML Files.
Pace 3 – Create Loader scene
Now, within of Unity, the first thing I did was create a Loader scene that contains a Loader game object, which volition be used to load the XML file, read all the data, and assign that data to a Listing that I can apply in my game. So do this:
- Create a new scene called TestScene. TestScene can remain empty.
- Salvage TestScene and create a new scene in Unity. This volition be your Loader scene. Create an empty game object in your hierarchy. Call it whatever yous want.
- On the empty game object, add a new C# script as a component. Proper noun it whatsoever y'all want. I named mine Loader. Open the script in MonoDevelop (or any IDE you use)
My Loader scene looks like this:
Stride 4 – Add together Coding
One time you have the Loader script open in your IDE, re-create and paste this code (I apologize if the formatting is messed up). I accept provided comments to explicate the logic behind everything:
using UnityEngine;
using Arrangement.Collections;
using Organisation.Collections.Generic; //Needed for Lists
using System.Xml; //Needed for XML functionality
using Organization.Xml.Serialization; //Needed for XML Functionality
using System.IO;
using System.Xml.Linq; //Needed for XDocument
public grade Loader : MonoBehaviour {
XDocument xmlDoc; //create Xdocument. Will be used after to read XML file IEnumerable<XElement> items; //Create an Ienumerable list. Will exist used to store XML Items. List <XMLData> data = new List <XMLData>(); //Initialize Listing of XMLData objects.
int iteration = 0, pageNum = 0;
string charText, dialogueText;
bool finishedLoading = false;
void Get-go ()
{
DontDestroyOnLoad (gameObject); //Allows Loader to bear over into new scene LoadXML (); //Loads XML File. Code below. StartCoroutine ("AssignData"); //Starts assigning XML data to data List. Code below
}
void Update ()
{
if (finishedLoading)
{
Application.LoadLevel ("TestScene"); //Just happens if coroutine is finished finishedLoading = false;
}
}
void LoadXML()
{
//Assigning Xdocument xmlDoc. Loads the xml file from the file path listed. xmlDoc = XDocument.Load( "Assets/Resources/XML Files/circles_test.xml" );
//This basically breaks down the XML Certificate into XML Elements. Used afterwards. items = xmlDoc.Descendants( "page" ).Elements ();
}
//this is our coroutine that volition actually read and assign the XML data to our Listing IEnumerator AssignData()
{
/*foreach allows us to look at every Element of our XML file and practise something with each one. Basically, this line is saying "for each element in the xml certificate, do something.
*/ foreach (var item in items)
{
/*Determine if the <page number> attribute in the XML is equal to whatever our current iteration of the loop is. If information technology is, then we want to assign our variables to the value of the XML Element that we demand.
*/
if(item.Parent.Aspect("number").Value == iteration.ToString ())
{
pageNum = int.Parse (item.Parent.Aspect ("number").Value); charText = detail.Parent.Element("proper noun").Value.Trim (); dialogueText = particular.Parent.Chemical element ("dialogue").Value.Trim ();
/*Create a new Index in the List, which volition exist a new XMLData object and pass the previously assigned variables as arguments so they get assigned to the new object'due south variables.
*/
data.Add together (new XMLData(pageNum, charText, dialogueText));
/*To test and brand sure the information has been practical to properly, print out the musicClip name from the data list'due south electric current index. This will allow us know if the objects in the list take been created successfully and if their variables have been assigned the right values.
*/
Debug.Log (information[iteration].dialogueText);
iteration++; //increment the iteration by 1
}
}
finishedLoading = truthful; //tell the plan that nosotros've finished loading data. yield return null;
}
}
// This class is used to assign our XML Information to objects in a list so we tin phone call on them later. public class XMLData {
public int pageNum;
public string charText, dialogueText;
// Create a constructor that will have multiple arguments that can be assigned to our variables. public XMLData (int page, string grapheme, cord dialogue)
{
pageNum = folio;
charText = grapheme;
dialogueText = dialogue;
}
}
STEP 5 – Test
Now, if you lot play the Loader scene, all the data in the XML file should go loaded. If you're using the XML information I provided, you lot should see something like this in your console:
This confirms that our List has been populated with the advisable number of objects with each one containing unique information equally per each page number. Also, you may non find it if your TestScene has nothing special in it, but your Loader object should carry over into the new level so you can call on the data whenever yous need to. In my bureaucracy in the following screenshot, you'll see all the items in my TestScene loaded alongside my Loader object:
Understanding Chemical element vs. Aspect
One thing I had difficulty with when I outset started working with XML files was the difference betwixt an Chemical element and an Aspect. This kind of lawmaking can be very confusing if you lot don't larn what some of this terminology means. An element is, essentially, a tag in an XML file. So, my <name> tag is technically an element. Any that chemical element contains is the data that is in between the <name> and </name> tags. Then, when I phone call particular.Parent.Element("proper noun").Value, I'k calling on the value contained between the <proper name> and </proper name> tags. Elements are different than Attributes. Attributes are variables that are assigned values inside an element. For example: <page number = "1"> In this example, "number" is an attribute of the "Page" Element. I use this aspect as an if statement to make up one's mind which page our for each loop is reading. Within that if statement, I assign our variables the values that are contained within that specific page number. This works because the if statement only executes if our current iteration of the loop is looking inside the specific page number that I desire.
Boosted Info: Sound and Text
In my game, I'grand also using information technology to load AudioClip files for music and audio furnishings using lines like this:
musicClip = Resources.Load ("Music/" + particular.Parent.Element ("music").Value.Trim ().ToString ()) as AudioClip;
I've as well written text from an XML document directly into a Text UI object similar this:
foreach ( var proper noun in names )
{
// is the element named "proper name" and is it a child of the current page number?
if(name.Proper name == "proper noun" && name.Parent.Attribute("number").Value ==
pageNum.ToString ())
{
nameUI.text = proper name.Value.Trim ();
}
}
Decision
In conclusion, this is a rather primitive example of XML Reading. Hopefully information technology can serve as a starting point for anybody who may be starting off in this realm. One time yous understand the basics of XML reading in Unity, you tin further refine your code and create an incredibly dynamic organization. I hope this helps you calculation an XML file in Unity. Please experience free to leave comments or feedback on the commodity. I am sure there are areas where I could exist doing this more than efficiently. Programming is a collaborative effort then please feel free to exit a annotate and discuss what could be done differently or how this could be implemented in a dissimilar style. Thank you!
Blogger: Marking Philipp, Application Engineer at Studica
Source: https://blog.studica.com/read-xml-file-in-unity
0 Response to "Unity How to Format Text File to Be Read in as a Dictionary"
Post a Comment