====== 062 セーブデータの読み書き対応(XMLファイルの読み書き) ====== ===== 概要 ===== セーブデータの読み書きをXMLファイルの読み書きで実装します。 Android 端末の本体書き込みで確認。SDカードの場合や、iOSは環境が無いので未確認です。 ==== ソースコード ==== using UnityEngine; using System.Collections; using System.Runtime.InteropServices; using System; using System.Text; using System.Xml; // XmlDocument. using System.IO; // StreamReader. using System.Collections.Generic; // Dictionary. // // // セーブデータ設定クラス // // // public class SaveLoadXml { enum Tag { player } enum Player { Player_00 = 0, Max = 1 }; private static Dictionary data = new Dictionary(); private static XmlDocument xmlDoc = new XmlDocument(); private static String data_location = "/SaveLoad.xml"; private static String data_root_tag = "saveload"; // // 値のセット. // _tag Tag.player.ToString(); // _value Player.Player_00 // public static void SetValue( String _tag, int _value ) { data[ _tag ] = _value; } // // 値のゲット. // _tag Tag.player.ToString(); // public static int GetValue( String _tag ) { return data[ _tag ]; } // // 作成. // public static void Create() { Debug.Log( "Create" ); String path = Application.persistentDataPath + data_location; Debug.Log( path ); XmlWriter writer = XmlWriter.Create( path ); writer.WriteRaw("\n"); writer.WriteRaw(" 0\n"); writer.WriteRaw("\n"); writer.Flush (); writer.Close (); } // // 読み込み. // public static void Load() { Debug.Log( "Load" ); data.Clear(); // File 読み込み. String path = Application.persistentDataPath + data_location; if ( !File.Exists ( path ) ) { Create(); } // XML読み込み. xmlDoc.Load( path ); XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName( data_root_tag ); foreach( XmlNode x in xmlNodeList ) { XmlNodeList xmlChildNodeList = x.ChildNodes; foreach( XmlNode y in xmlChildNodeList ) { Debug.Log( "tag " + y.Name ); Debug.Log( "value " + y.InnerText ); data.Add( y.Name, int.Parse( y.InnerText ) ); } } } // // 書き込み. // public static void Save() { Debug.Log( "Save" ); // File 読み込み. String path = Application.persistentDataPath + data_location; XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName( data_root_tag ); foreach( XmlNode x in xmlNodeList ) { XmlNodeList xmlChildNodeList = x.ChildNodes; foreach( XmlNode y in xmlChildNodeList ) { // 値変更テスト. // SetValue( Tag.player.ToString(), 9999 ); y.InnerText = data[ y.Name ].ToString(); Debug.Log( "tag " + y.Name ); Debug.Log( "value " + y.InnerText ); } } xmlDoc.Save( path ); } }