Skip to content

Instantly share code, notes, and snippets.

@enue
Last active December 22, 2016 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enue/12483c01f22200ceb12889bb929d8bdf to your computer and use it in GitHub Desktop.
Save enue/12483c01f22200ceb12889bb929d8bdf to your computer and use it in GitHub Desktop.
[Unity] Xmlを読み込める汎用ScriptableObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.Linq;
namespace TSKT
{
public class XmlObject : ScriptableObject
{
[System.Serializable]
public struct Attribute
{
public string name;
public string value;
public Attribute(XmlAttribute source)
{
name = source.Name;
value = source.Value;
}
}
[System.Serializable]
public class Node
{
public string name;
[Multiline]
public string text;
public Attribute[] attributes;
public Node[] nodes;
public Node(XmlNode source)
{
name = source.Name;
if (source.Attributes != null)
{
attributes = source.Attributes
.Cast<XmlAttribute>()
.Select(_ => new Attribute(_))
.ToArray();
}
var xmlNodes = source.ChildNodes.Cast<XmlNode>();
nodes = xmlNodes
.Where(_ => _.NodeType != XmlNodeType.XmlDeclaration)
.Where(_ => _.NodeType != XmlNodeType.Text)
.Select(_ => new Node(_))
.ToArray();
var textNode = xmlNodes.FirstOrDefault(_ => _.NodeType == XmlNodeType.Text);
if (textNode != null)
{
text = textNode.Value;
}
}
}
public Node root;
#if UNITY_EDITOR
[SerializeField]
TextAsset source;
public void Build()
{
var doc = new XmlDocument();
doc.LoadXml(source.text);
root = new Node(doc);
UnityEditor.EditorUtility.SetDirty(this);
}
#endif
}
}
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Linq;
namespace TSKT
{
[CustomEditor(typeof(XmlObject))]
public class XmlObjectEditor : Editor
{
public override void OnInspectorGUI()
{
if (GUILayout.Button("Build"))
{
var data = target as XmlObject;
data.Build();
}
DrawDefaultInspector();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment