Skip to content

Instantly share code, notes, and snippets.

@GOROman
Last active March 16, 2020 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save GOROman/c07291d27d572a7e2372 to your computer and use it in GitHub Desktop.
Save GOROman/c07291d27d572a7e2372 to your computer and use it in GitHub Desktop.
Unityで構造体をセーブ・ロード(XMLにシリアライズ)
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 );
}
}
}
<?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