- Home /
novice: dynamically load xml or text and populate textfield (quiz style game)
Can anyone point me to a simple demo that dynamically loads a text file and populates several textfields in the UI? I'm building a quiz style game and don't want to 'bake in' all the questions.
Comment
Answer by Louis Watson · Sep 21, 2014 at 05:24 AM
Ok I was bored and this is what I came up with:
Consider the following xml:
<?xml version="1.0" ?>
<Item>
<Name>Sample</Name>
<Description>Sample Description</Description>
</Item>
Then attach the following script to a canvas element or group that contains text fields named "Name" and "Description":
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Xml;
public class Binder : MonoBehaviour
{
public TextAsset Text_Asset;
void OnEnable()
{
if (Text_Asset == null) throw new System.Exception("Text_Asset not defined on Binder Script!");
XmlDocument xd = new XmlDocument();
xd.LoadXml(Text_Asset.text);
if (xd.DocumentElement.HasChildNodes)
{
Dictionary<string, Text> textComponents = new Dictionary<string,Text>(2);
Text[] t = gameObject.GetComponentsInChildren<Text>();
foreach (Text itm in t)
textComponents.Add(itm.name, itm);
foreach (XmlNode node in xd.DocumentElement.ChildNodes)
{
if (textComponents.ContainsKey(node.Name))
textComponents[node.Name].text = node.InnerText;
}
}
}
}
Drop the xml file from the project window on to the Text_Asset field in the inspector for the script instance.