Search code examples
c#xmlunityscriptunity-game-engine

Unity 3D C# Strings.XML Methods


I'm attempting to create a method for Unity3D that will allow me to populate a UI via an XML file. i.e. Rather than naming each button and label, they can carry generic names like "progress button" or "large text" Then using the C# script be matched to the verbose name in the XML file.

I have searched extensively for tutorials, examples and guides but each that I have found has been overkill for what I am trying to accomplish.

Ideally, I'd like to provide an XML file using the following structure in the XML file:

<?xml version="1.0" encoding="utf-8"?>
<strings>
  <string name="progressBtn">Next</string>
  <string name="reverseBtn">Back</string>
  <string name="largeText">This is Large Text</string>
</strings>

I know how to dynamically change text in unity by accessing the properties of text-object's so I'm not worried about that step. What I have currently is this:

using UnityEngine;
using System.Collections;
using System.Xml;
using System.IO;

public class textParser : MonoBehaviour
{

public TextAsset targetXMLFile;
public GameObject uiObjectText;
string targetString;

// Use this for initialization
void Start ()
{
    checkFile();//Check for strings file.
    checkTarget(uiObjectText.name);//Check for the object name in the GUI object
}

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

//Check for strings file.
void checkFile()
{
    if (targetXMLFile == null) //If is Null, Log an Error
    {
        print("Error: target text file not loaded!");
    }
    else // If something, log the file name
    {
        print(targetXMLFile.name + " Target text file loaded!");
    }
}

//Check for the object name in the GUI object
void checkTarget(string target)
{
    if (target == null) //If is Null, Log an Error
    {
        print("Error: Unable to extract target ui object name!");
    }
    else// if something, Log the GUI Object name
    {
        print("Found: " + target + " In GUI.");
    }
}
}

Obviously very basic, but it works. I know I need to use the XML libraries to accomplish my search (String matching I understand). Getting to that step is what eludes me.

Any tutorials that are much more towards this use of XML I'd love to look at, or if anyone could give me an idea of what methods I need to access to accomplish this. Personally ,I'd love to understand the verbose process behind what I am trying to do if anyone could provide a link to example code.

Thanks in Advance!


Solution

  • You can use the Xml.Serialization from .NET:

    https://unitygem.wordpress.com/xml-serialisation/