Last active
March 16, 2020 07:16
-
-
Save GOROman/c07291d27d572a7e2372 to your computer and use it in GitHub Desktop.
Unityで構造体をセーブ・ロード(XMLにシリアライズ)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.IO; | |
using System.Xml; | |
using System.Xml.Serialization; | |
// 保存したい構造体 | |
[System.Serializable] | |
public struct Param | |
{ | |
public int a; | |
public float b; | |
public Vector3 c; | |
} | |
public class Serialize : MonoBehaviour { | |
public Param param; | |
void Update() { | |
// S を押すとセーブ | |
if ( Input.GetKeyDown( KeyCode.S ) ) { | |
Save( "Test.xml" ); | |
} | |
// L を押すとロード | |
if ( Input.GetKeyDown( KeyCode.L ) ) { | |
Load( "Test.xml" ); | |
} | |
} | |
// ファイルへロード | |
void Load( string filename ) { | |
var serializer = new XmlSerializer( typeof( Param ) ); | |
using( var stream = new FileStream( filename, FileMode.Open ) ) { | |
param = (Param)serializer.Deserialize( stream ); | |
} | |
} | |
// ファイルへセーブ | |
void Save( string filename ) { | |
var serializer = new XmlSerializer( typeof( Param ) ); | |
using( var stream = new FileStream( filename, FileMode.Create ) ) { | |
serializer.Serialize( stream, param ); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="shift_jis"?> | |
<Param xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> | |
<a>10</a> | |
<b>20</b> | |
<c> | |
<x>0.5</x> | |
<y>0</y> | |
<z>0</z> | |
</c> | |
</Param> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment